I have a problem with writing function of jSSC. My Arduino Uno board seems not getting data from my Java program.
I have a stepper motor controlled by Arduino Uno board. I made a simple program that has 2 buttons. One is for CW rotation and the other is CCW rotation. CW button sends 'H' char and CCW button sends 'L' char. Now I have:
I checked from Arduino IDE serial console my Arduino program works correct. When I send 'H' the motor turns CW and with 'L' the motor turns CCW.
I made a program in Processing with two buttons sending 'H' and 'L'. It worked.
I made a Java program with JSSC with two buttons sending 'H' and 'L'. IT FAILED.
When I push one of the buttons in my program I see "L" light on the board blinks 3-4 times but nothing happens.
I tried getting data from my board with JSSC and it worked. It seems the problem is in writing function.
I checked with another Arduino Uno board but the result is the same.
My Java program uses serialPort.writeByte((byte)'H'); and serialPort.writeByte((byte)'L');
Any ideas?
Did you try setting the parameters for flow control. Since while writing to the interface, it requires a permission.
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE,false,true);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0,RTSEnable,DTSEnable);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
Can it be a reset-related problem? Maybe your java function uses the DTR pin, which is connected to the RESET pin; so when you try to send data instead you are just resetting the board.
If you want to test you can make another led blink at startup or send something through the serial interface at setup. If you get that feedback try looking at the way to disable DTR ;)
You can refactor Processing's Serial class (which works pretty well) to avoid PApplet if you don't plan to use it in your java project:
/*
PSerial - class for serial port goodness
Part of the Processing project - http://processing.org
Copyright (c) 2004-05 Ben Fry & Casey Reas
Reworked by Gottfried Haider as part of GSOC 2013
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
import java.lang.reflect.Method;
import java.util.Map;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
import jssc.SerialPortList;
public class Serial implements SerialPortEventListener {
Object parent;
public SerialPort port;
Method serialAvailableMethod;
Method serialEventMethod;
byte[] buffer = new byte[32768];
int inBuffer = 0;
int readOffset = 0;
int bufferUntilSize = 1;
byte bufferUntilByte = 0;
volatile boolean invokeSerialAvailable = false;
// Things we are currently not exposing:
// * hardware flow control
// * state of the RING, RLSD line
// * sending breaks
public Serial(Object parent) {
this(parent, "COM1", 9600, 'N', 8, 1);
}
public Serial(Object parent, int baudRate) {
this(parent, "COM1", baudRate, 'N', 8, 1);
}
public Serial(Object parent, String portName) {
this(parent, portName, 9600, 'N', 8, 1);
}
public Serial(Object parent, String portName, int baudRate) {
this(parent, portName, baudRate, 'N', 8, 1);
}
public Serial(Object parent, String portName, int baudRate, char parity, int dataBits, float stopBits) {
this.parent = parent;
//parent.registerMethod("dispose", this);
//parent.registerMethod("pre", this);
// setup parity
if (parity == 'O') {
parity = SerialPort.PARITY_ODD;
} else if (parity == 'E') {
parity = SerialPort.PARITY_EVEN;
} else if (parity == 'M') {
parity = SerialPort.PARITY_MARK;
} else if (parity == 'S') {
parity = SerialPort.PARITY_SPACE;
} else {
parity = SerialPort.PARITY_NONE;
}
// setup stop bits
int stopBitsIdx = SerialPort.STOPBITS_1;
if (stopBits == 1.5f) {
stopBitsIdx = SerialPort.STOPBITS_1_5;
} else if (stopBits == 2) {
stopBitsIdx = SerialPort.STOPBITS_2;
}
port = new SerialPort(portName);
try {
// the native open() call is not using O_NONBLOCK, so this might block for certain operations (see write())
port.openPort();
port.setParams(baudRate, dataBits, stopBitsIdx, parity);
// we could register more events here
port.addEventListener(this, SerialPort.MASK_RXCHAR);
} catch (SerialPortException e) {
// this used to be a RuntimeException before, so stick with it
throw new RuntimeException("Error opening serial port " + e.getPortName() + ": " + e.getExceptionType());
}
serialEventMethod = findCallback("serialEvent");
serialAvailableMethod = findCallback("serialAvailable");
}
private Method findCallback(final String name) {
try {
return parent.getClass().getMethod(name, this.getClass());
} catch (Exception e) {
}
// Permit callback(Object) as alternative to callback(Serial).
try {
return parent.getClass().getMethod(name, Object.class);
} catch (Exception e) {
}
return null;
}
public void dispose() {
stop();
}
public void pre() {
if (serialAvailableMethod != null && invokeSerialAvailable) {
invokeSerialAvailable = false;
try {
serialAvailableMethod.invoke(parent, this);
} catch (Exception e) {
System.err.println("Error, disabling serialAvailable() for "+port.getPortName());
System.err.println(e.getLocalizedMessage());
serialAvailableMethod = null;
}
}
}
public int available() {
return (inBuffer-readOffset);
}
public void buffer(int size) {
bufferUntilSize = size;
}
public void bufferUntil(int inByte) {
bufferUntilSize = 0;
bufferUntilByte = (byte)inByte;
}
public void clear() {
synchronized (buffer) {
inBuffer = 0;
readOffset = 0;
}
}
public boolean getCTS() {
try {
return port.isCTS();
} catch (SerialPortException e) {
throw new RuntimeException("Error reading the CTS line: " + e.getExceptionType());
}
}
public boolean getDSR() {
try {
return port.isDSR();
} catch (SerialPortException e) {
throw new RuntimeException("Error reading the DSR line: " + e.getExceptionType());
}
}
public static Map<String, String> getProperties(String portName) {
return SerialPortList.getPortProperties(portName);
}
public int last() {
if (inBuffer == readOffset) {
return -1;
}
synchronized (buffer) {
int ret = buffer[inBuffer-1] & 0xFF;
inBuffer = 0;
readOffset = 0;
return ret;
}
}
public char lastChar() {
return (char)last();
}
public static String[] list() {
// returns list sorted alphabetically, thus cu.* comes before tty.*
// this was different with RXTX
return SerialPortList.getPortNames();
}
public int read() {
if (inBuffer == readOffset) {
return -1;
}
synchronized (buffer) {
int ret = buffer[readOffset++] & 0xFF;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return ret;
}
}
public byte[] readBytes() {
if (inBuffer == readOffset) {
return null;
}
synchronized (buffer) {
byte[] ret = new byte[inBuffer-readOffset];
System.arraycopy(buffer, readOffset, ret, 0, ret.length);
inBuffer = 0;
readOffset = 0;
return ret;
}
}
public int readBytes(byte[] dest) {
if (inBuffer == readOffset) {
return 0;
}
synchronized (buffer) {
int toCopy = inBuffer-readOffset;
if (dest.length < toCopy) {
toCopy = dest.length;
}
System.arraycopy(buffer, readOffset, dest, 0, toCopy);
readOffset += toCopy;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return toCopy;
}
}
public byte[] readBytesUntil(int inByte) {
if (inBuffer == readOffset) {
return null;
}
synchronized (buffer) {
// look for needle in buffer
int found = -1;
for (int i=readOffset; i < inBuffer; i++) {
if (buffer[i] == (byte)inByte) {
found = i;
break;
}
}
if (found == -1) {
return null;
}
int toCopy = found-readOffset+1;
byte[] dest = new byte[toCopy];
System.arraycopy(buffer, readOffset, dest, 0, toCopy);
readOffset += toCopy;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return dest;
}
}
public int readBytesUntil(int inByte, byte[] dest) {
if (inBuffer == readOffset) {
return 0;
}
synchronized (buffer) {
// look for needle in buffer
int found = -1;
for (int i=readOffset; i < inBuffer; i++) {
if (buffer[i] == (byte)inByte) {
found = i;
break;
}
}
if (found == -1) {
return 0;
}
// check if bytes to copy fit in dest
int toCopy = found-readOffset+1;
if (dest.length < toCopy) {
System.err.println( "The buffer passed to readBytesUntil() is to small " +
"to contain " + toCopy + " bytes up to and including " +
"char " + (byte)inByte);
return -1;
}
System.arraycopy(buffer, readOffset, dest, 0, toCopy);
readOffset += toCopy;
if (inBuffer == readOffset) {
inBuffer = 0;
readOffset = 0;
}
return toCopy;
}
}
public char readChar() {
return (char) read();
}
public String readString() {
if (inBuffer == readOffset) {
return null;
}
return new String(readBytes());
}
public String readStringUntil(int inByte) {
byte temp[] = readBytesUntil(inByte);
if (temp == null) {
return null;
} else {
return new String(temp);
}
}
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPortEvent.RXCHAR) {
int toRead;
try {
while (0 < (toRead = port.getInputBufferBytesCount())) {
// this method can be called from the context of another thread
synchronized (buffer) {
// read one byte at a time if the sketch is using serialEvent
if (serialEventMethod != null) {
toRead = 1;
}
// enlarge buffer if necessary
if (buffer.length < inBuffer+toRead) {
byte temp[] = new byte[buffer.length<<1];
System.arraycopy(buffer, 0, temp, 0, inBuffer);
buffer = temp;
}
// read an array of bytes and copy it into our buffer
byte[] read = port.readBytes(toRead);
System.arraycopy(read, 0, buffer, inBuffer, read.length);
inBuffer += read.length;
}
if (serialEventMethod != null) {
if ((0 < bufferUntilSize && bufferUntilSize <= inBuffer-readOffset) ||
(0 == bufferUntilSize && bufferUntilByte == buffer[inBuffer-1])) {
try {
// serialEvent() is invoked in the context of the current (serial) thread
// which means that serialization and atomic variables need to be used to
// guarantee reliable operation (and better not draw() etc..)
// serialAvailable() does not provide any real benefits over using
// available() and read() inside draw - but this function has no
// thread-safety issues since it's being invoked during pre in the context
// of the Processing applet
serialEventMethod.invoke(parent, this);
} catch (Exception e) {
System.err.println("Error, disabling serialEvent() for "+port.getPortName());
System.err.println(e.getLocalizedMessage());
serialEventMethod = null;
}
}
}
invokeSerialAvailable = true;
}
} catch (SerialPortException e) {
throw new RuntimeException("Error reading from serial port " + e.getPortName() + ": " + e.getExceptionType());
}
}
}
public void setDTR(boolean state) {
// there is no way to influence the behavior of the DTR line when opening the serial port
// this means that at least on Linux and OS X, Arduino devices are always reset
try {
port.setDTR(state);
} catch (SerialPortException e) {
throw new RuntimeException("Error setting the DTR line: " + e.getExceptionType());
}
}
public void setRTS(boolean state) {
try {
port.setRTS(state);
} catch (SerialPortException e) {
throw new RuntimeException("Error setting the RTS line: " + e.getExceptionType());
}
}
public void stop() {
try {
port.closePort();
} catch (SerialPortException e) {
// ignored
}
inBuffer = 0;
readOffset = 0;
}
public void write(byte[] src) {
try {
// this might block if the serial device is not yet ready (esp. tty devices under OS X)
port.writeBytes(src);
// we used to call flush() here
} catch (SerialPortException e) {
throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
}
}
public void write(int src) {
try {
port.writeInt(src);
} catch (SerialPortException e) {
throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
}
}
public void write(String src) {
try {
port.writeString(src);
} catch (SerialPortException e) {
throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
}
}
}
Here's an example class using the above:
public class SerialTest {
public static void main(String[] args) {
try{
Serial serial = new Serial(new SerialTest(),"/dev/tty.usbmodemfd121",115200);
serial.write("H");
serial.write("L");//can also try serial.write((int)'L');
}catch(Exception e){
System.err.println("serial not connected!");
}
}
public void serialAvailable(Serial s){
System.out.println(s.toString());
}
public void serialEvent(Serial s){
System.out.print("from serial:");
System.out.println(s.read());
}
}
Be sure to change the port and baud rate to what your Arduino Uno is using.
In Processing's serial library folder you'll also find the JNI native libraries.
For example on Windows:
C:\Program Files\processing-2.1.2\modes\java\libraries\serial\library
Where the dll would reside in the windows32 and windows64 folders, depending on what you plan to use.
The Serial class above is pretty much the same as C:\Program Files\processing-2.1.2\modes\java\libraries\serial\src\processing\serial/Serial.java replacing PApplet with Object.
Also, here is the Processing Serial library reference
Related
I'm trying to intercept packets and be able to block them from incoming/outgoing, for a specific domain
In order to do that i made my (java) program adds the domain to the hosts file with a redirection to my own public ipv4 adress (this doesnt matter it just can't be the real IP and i must be able to intercept it, redirecting to my own IP makes sure nobody else in the world receives it). Secondly, i make the program listen to that signal and resend it on a different source port to the real server. (Checksum changes have been taken care of) Now the plan is to receive the response and do the exact same thing, but now by editting the source ip (my own public IP in this case) and the destination port
This should create a program where i'm a kind of middle men between a connection
But it doesnt work as expected, the moment im getting a response of the server (flags SYN/ACK), it's automatically sending them back a RST flag (IPv4/TCP) from the random chosen port by me which isnt the same as the port of the real client
I don't know if there are better ways to do this (there probably are) and how to prevent the problem I'm having, I couldn't really find similiar things to this on the internet. Any kind of help/hints would be appreciated
Keep in mind that I'm using jnetpscape at this moment and it would be nice to continue at what i'm doing right now
EDIT (code):
this is the "HConnection" class (not fully showed but all essential things):
public class HConnection {
private volatile int state = -1; // current state of the program
private volatile boolean HostFileEdited = false;
private volatile String domain = null;
private volatile boolean waitingConnection = false;
private volatile String ipOfDomain = null; // string of the server adress
private volatile byte[] ipofdomb; //4 bytes of the server adress
private volatile String myIpAdr = null; //my IP adress
private volatile byte[] myIpb; //my public IP in 4 bytes
private volatile byte[] port = null; //port of proxy
private volatile byte[] falseport = null; //port of client
private volatile ServerSocket server;
public HConnection() {
try {
server = new ServerSocket(0);
byte[] tempPortb = ByteBuffer.allocate(4).putInt(server.getLocalPort()).array();
System.out.println(server.getLocalPort());
port = new byte[]{tempPortb[2], tempPortb[3]};
(new Thread() {
public void run() {
try {
server.accept();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}).start();
state = 0;
} catch (UnknownHostException e) {System.out.println("fail");} catch (IOException e) {System.out.println("fail");}
}
public String getPublicIP () {
try{
myIpAdr = new BufferedReader(new InputStreamReader(new URL("http://checkip.amazonaws.com/").openStream())).readLine();
System.out.println(myIpAdr);
InetAddress ip = InetAddress.getByName(myIpAdr);
myIpb = ip.getAddress();
return myIpAdr;
}
catch (Exception e){}
return null;
}
public void setUrl(String domain) {
this.domain = domain;
}
public int getState() {
return state;
}
public void prepare() {
try{
URL urlofsite = new URL("https://"+domain);
InetAddress address = InetAddress.getByName(urlofsite.getHost());
ipOfDomain = address.getHostAddress();
System.out.println(ipOfDomain);
ipofdomb = address.getAddress();
addToHostsFile(getPublicIP() + "\t" + domain);
state = 1;
}
catch(Exception e){}
}
public void abort() {
removeFromHostsFile(domain);
HostFileEdited = false;
state = -1;
try {
server.close();
} catch (IOException e) { }
waitingConnection = false;
}
public void awaitConnection() {
if (state == 1) {
waitingConnection = true;
System.out.println("stap1");
StringBuilder errbuf = new StringBuilder(); // For any error msgs
int snaplen = 64 * 1024; // Capture all packets, no truncation
int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
int timeout = 0; // 10 seconds in millis
Pcap pcap = Pcap.openLive("wlp4s0", snaplen, flags, timeout, errbuf);
if (pcap == null) {
System.err.printf("Error while opening device for capture: "
+ errbuf.toString());
return;
}
PcapHeader hdr = new PcapHeader(JMemory.POINTER);
JBuffer buf = new JBuffer(JMemory.POINTER);
int id = JRegistry.mapDLTToId(pcap.datalink());
while (HostFileEdited && waitingConnection && state == 1 && pcap.nextEx(hdr, buf) == Pcap.NEXT_EX_OK) {
PcapPacket packet = new PcapPacket(hdr, buf);
try {
packet.scan(id);
TcpPacket pkt = new TcpPacket(packet);
if (pkt.isTcp()) {
if (pkt.destinationIPequals(myIpAdr) && pkt.getDestinationPort() == 443 && (falseport == null || Arrays.equals(pkt.getSourcePortb(), falseport))) {
if (falseport == null) {
falseport = pkt.getSourcePortb();
}
pkt.changeDestinationIP(ipofdomb);
pkt.changeSourcePort(port);
pkt.iPchecksumFix();
pkt.tcPchecksumFix();
ByteBuffer b = ByteBuffer.wrap(pkt.getPacketInBytes());
System.out.println("10");
System.out.println("OUT"+ (pcap.sendPacket(b)));
}
else if (pkt.sourceIPequals(ipOfDomain) && pkt.getSourcePort() == 443 && falseport != null && Arrays.equals(pkt.getDestinationPortb(),port) ) {
pkt.changeSourceIP(myIpb);
pkt.changeDestinationPort(falseport);
pkt.iPchecksumFix();
pkt.tcPchecksumFix();
ByteBuffer b = ByteBuffer.wrap(pkt.getPacketInBytes());
System.out.println("IN"+ pcap.sendPacket(b));
}
}
}
catch (Exception e) {}
}
System.out.println("stap2");
if (state == 1 && waitingConnection == true) state = 2;
waitingConnection = false;
}
}
}
The "awaitConnection()" method is were currently most things are happening. But this will only be the beginning of my program
HConnection is called from the main class (SWT Designer):
private Button btnNewButton_1;
private HConnection connectie;
private void btnConnect_clicked(SelectionEvent e) throws InterruptedException {
if (btnNewButton_1.getText().equals("Connect")) {
String Url = combo.getText();
connectie = new HConnection();
connectie.setUrl(Url);
connectie.prepare();
lblNewLabel_2.setText("Waiting -> client");
new Thread(new Runnable() {
public void run() {
connectie.awaitConnection();
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (connectie.getState() == 2) {
lblNewLabel_2.setText("Replacing URL");
}
else {
lblNewLabel_2.setText("Failed");
connectie.abort();
btnNewButton_1.setText("Connect");
}
}
});
if (connectie.getState() == 2) {
// go on with the rest of the program
}
}
}).start();
btnNewButton_1.setText("Abort");
}
else if(btnNewButton_1.getText().equals("Abort")) {
connectie.abort();
lblNewLabel_2.setText("Aborted");
btnNewButton_1.setText("Connect");
}
}
The following code accepts a connection, but doesn't maintain a reference to the resulting Socket instance. This Socket is eligible for garbage collection, and when that happens, it is automatically closed. A client sending data to that socket will then receive an RST.
public void run() {
try {
server.accept();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
I am currently programming a simple application that takes input from a midi device and outputs the corresponding sound. I have gotten everything to work now, but there is two problems: First of all, when i plug in a midi device AFTER the program has started or disconnect it while the program is running, it will not get recognized. Second of all, the latency is very high on OSX, Linux (Raspbian) and Windows alike. Does anyone know the solution to either of these issues?
Here is what i have so far:
The MidiHandler class reads the input and synthesizes the sound
public class MidiHandler {
MidiDevice device;
MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
List<Transmitter> transmitters;
MidiInputReceiver reciever;
public MidiHandler() {
for (int i = 0; i < infos.length; i++) {
try {
this.device = MidiSystem.getMidiDevice(this.infos[i]);
// does the device have any transmitters?
// if it does, add it to the device list
System.out.println(this.infos[i]);
// get all transmitters
this.transmitters = this.device.getTransmitters();
// using my own MidiInputReceiver
this.reciever = new MidiInputReceiver(this.device
.getDeviceInfo().toString());
// and for each transmitter
for (int j = 0; j < this.transmitters.size(); j++) {
// create a new receiver
this.transmitters.get(j).setReceiver(this.reciever);
}
Transmitter trans = this.device.getTransmitter();
trans.setReceiver(new MidiInputReceiver(this.device
.getDeviceInfo().toString()));
this.device.open();
} catch (MidiUnavailableException e) {
}
}
}
public void playNote(byte b) {
reciever.playNote(b);
}
public void stopNote(byte b) {
reciever.stopNote(b);
}
public void close() {
for (int i = 0; i < this.transmitters.size(); ++i) {
this.transmitters.get(i).close();
}
this.reciever.close();
this.device.close();
}
public String getInfos() {
String infos = "";
for (int i = 0; i < this.infos.length; i++) {
infos += "\n" + this.infos[i] + " ";
}
return infos;
}
// tried to write my own class. I thought the send method handles an
// MidiEvents sent to it
public class MidiInputReceiver implements Receiver {
Synthesizer synth;
MidiChannel[] mc;
Instrument[] instr;
int instrument;
int channel;
public MidiInputReceiver(String name) {
try {
patcher p = new patcher();
this.instrument = p.getInstrument();
this.channel = p.getChannel();
this.synth = MidiSystem.getSynthesizer();
this.synth.open();
this.mc = synth.getChannels();
instr = synth.getDefaultSoundbank().getInstruments();
this.synth.loadInstrument(instr[1]);
mc[this.channel].programChange(0, this.instrument);
} catch (MidiUnavailableException e) {
e.printStackTrace();
System.exit(1);
}
}
public void send(MidiMessage msg, long timeStamp) {
/*
* Use to display midi message
for (int i = 0; i < msg.getMessage().length; i++) {
System.out.print("[" + msg.getMessage()[i] + "] ");
}
System.out.println();
*/
if (msg.getMessage()[0] == -112) {
mc[this.channel].noteOn(msg.getMessage()[1],
msg.getMessage()[2] + 1000);
}
if (msg.getMessage()[0] == -128) {
mc[this.channel].noteOff(msg.getMessage()[1],
msg.getMessage()[2] + 1000);
}
}
public void playNote(byte b) {
mc[this.channel].noteOn(b, 1000);
}
public void stopNote(byte b) {
mc[this.channel].noteOff(b);
}
public void close() {
}
}
The Shell class contains the main method
public class Shell {
private static MidiHandler midi;
AudioServer server;
private Shell() {
}
/**
* The main method. Executes via BufferedReader, to communicate with the
* user
*
* #param args
* Command line parameter
* #throws IOException
* IOExeption can occur
*/
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
execute(in);
}
/**
* Method used for general interaction with the user. Utilizes a
* BufferedReader to read inputs, then proceeds to analyze the input for
* predefined commands
*
* #param in
* The BufferedReader in use
* #throws IOException
* #throws ParseException
*/
private static void execute(BufferedReader in) throws IOException {
boolean quit = false;
while (!quit) {
midi = new MidiHandler();
System.out.print("midi> ");
String input;
input = in.readLine(); // read line
if (input == null | input.isEmpty()) {
break;
} // No command given?
// First character is always the command.
char command = Character.toLowerCase(input.charAt(0));
try {
switch (command) {
case 'n':
midi = new MidiHandler();
break;
case 'c':
midi.close();
break;
case 'p':
midi.playNote((byte) 60);
break;
case 's':
midi.stopNote((byte) 60);
case 'q':
midi.close();
quit = true;
System.exit(0);
break;
default:
System.out.println("Unknown command");
break;
}
} catch (NumberFormatException e) {
System.out.println("Invalid parameter");
}
}
}
Any help would be greatly appreciated. Thanks in advance.
I'm working on implements a tree that represent electric circus (without any circles, as in this picture)
I use this implementation:
Binary_Oprtator
public abstract class Binary_Oprtator {
abstract int calc(int x, int y);
#Override
public String toString() {
return super.toString().substring(0, super.toString().indexOf('#'));
}
}
And gate
public class and extends Binary_Oprtator {
public int calc(int x, int y){
return (x&y);
}
}
Or gate
public class or extends Binary_Oprtator {
public int calc(int x, int y){
return (x|y);
}
}
gate_node
public class gate_node {
gate_node father_c;
gate_node right_c, left_c;
Binary_Oprtator op;
int value;
int right_v, left_v;
int array_index;
int arr_size;
boolean leaf;
boolean isRightChild;
public gate_node(Binary_Oprtator op, int array_index, int arr_size, boolean right) {
this.array_index = array_index;
this.arr_size = arr_size;
this.left_c = null;
this.right_c = null;
this.op = op;
right_v = left_v = -1;
this.leaf = false;
this.isRightChild = right;
}
void set_left_son(Binary_Oprtator op) {
this.left_c = new gate_node(op, array_index, arr_size / 2,false);
this.left_c.father_c = this;
this.left_c.leaf = false;
this.left_c.isRightChild = false;
}
void set_right_son(Binary_Oprtator op) {
this.right_c = new gate_node(op, array_index + arr_size / 2,
arr_size / 2,true);
this.right_c.father_c = this;
this.right_c.leaf = false;
this.right_c.isRightChild = true;
}
void set_left_son_as_leaf(Binary_Oprtator op) throws InterruptedException {
this.left_c = new gate_node(op, array_index, arr_size / 2,false);
this.left_c.father_c = this;
this.left_c.leaf = true;
this.left_c.left_v = main_class.arr[array_index];
this.left_c.right_v = main_class.arr[array_index + 1];
this.left_c.isRightChild = false;
main_class.queue.put(this.left_c);
}
void set_right_son_as_leaf(Binary_Oprtator op) throws InterruptedException {
this.right_c = new gate_node(op, array_index + arr_size / 2,
arr_size / 2,true);
this.right_c.father_c = this;
this.right_c.left_v = main_class.arr[array_index + 2];
this.right_c.right_v = main_class.arr[array_index + 3];
this.right_c.leaf = true;
this.right_c.isRightChild = true;
main_class.queue.put(this.right_c);
}
gate_node get_left() {
return this.left_c;
}
gate_node get_right() {
return this.right_c;
}
int compute() {
/*
* The following use of a static sInputCounter assumes that the
* static/global input array is ordered from left to right, irrespective
* of "depth".
*/
final int left, right;
if (this.left_c.leaf != true) {
left = this.left_c.compute();
} else {
left = this.left_c.op.calc(this.left_c.left_v, this.left_c.right_v);
}
if (this.right_c.leaf != true) {
right = this.right_c.compute();
} else {
right = this.right_c.op.calc(this.right_c.left_v,
this.right_c.right_v);
}
return op.calc(left, right);
}
int compute_with_print() {
/*
* The following use of a static sInputCounter assumes that the
* static/global input array is ordered from left to right, irrespective
* of "depth".
*/
final int left, right;
System.out.print(this.op + "(");
if (null != this.left_c) {
left = this.left_c.compute_with_print();
System.out.print(",");
} else {
left = main_class.arr[array_index];
System.out.print(left + ",");
}
if (null != this.right_c) {
right = this.right_c.compute_with_print();
System.out.print(")");
} else {
right = main_class.arr[array_index + 1];
System.out.print(right + ")");
}
return op.calc(left, right);
}
}
tree
public class tree {
gate_node head;
public tree(Binary_Oprtator op,int array_index,int arr_size) {
this.head = new gate_node(op,array_index,arr_size,true);
head.father_c=null;
}
void calc_head_value(){
int t_value = head.op.calc(head.left_v,head.right_v);
/* System.out.println(head.left_v+" "+head.op.toString()+" "+head.right_v+" = "+head.op.calc(head.left_v,head.right_v));
*/ head.value = t_value;
}
int compute() {
return head.compute();
}
int compute_with_print(){
return head.compute_with_print();
}
void set_left_son(Binary_Oprtator op){
head.left_c = new gate_node(op,head.array_index,head.arr_size/2,false);
head.left_c.father_c=head;
}
void set_right_son(Binary_Oprtator op){
head.right_c = new gate_node(op,head.array_index + head.arr_size/2,head.arr_size/2,true);
head.right_c.father_c=head;
}
void set_right_son_as_leaf(Binary_Oprtator op) throws InterruptedException {
head.right_c = new gate_node(op,head.array_index,head.arr_size/2,false);
head.right_c.father_c=head;
head.right_c.father_c = head;
head.right_c.left_v = main_class.arr[head.array_index + 2];
head.right_c.right_v = main_class.arr[head.array_index + 3];
head.right_c.leaf = true;
head.right_c.isRightChild = true;
main_class.queue.put(head.right_c);
}
void set_left_son_as_leaf(Binary_Oprtator op) throws InterruptedException {
head.left_c = new gate_node(op, head.array_index, head.arr_size / 2,false);
head.left_c.father_c = head;
head.left_c.leaf = true;
head.left_c.left_v = main_class.arr[head.array_index];
head.left_c.right_v = main_class.arr[head.array_index + 1];
head.left_c.isRightChild = false;
main_class.queue.put(head.left_c);
}
gate_node get_left(){
return head.left_c;
}
gate_node get_right(){
return head.right_c;
}
}
main_class
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class main_class {
public static int arr[] = { 1, 0, 0, 0, 1, 0, 0, 1 };
static final BlockingQueue<gate_node> queue = new ArrayBlockingQueue<>(6);
public static void main(String[] args) throws InterruptedException {
/*************************************
* compute using multi threads
************************************/
System.out.println("compute using Multi threading");
//start a consumer... wait for nodes to be insert into the queue
Consumer consumer = new Consumer();
consumer.start();
tree t = new tree(new and(), 0, arr.length);
t.set_left_son(new or());
t.get_left().set_left_son_as_leaf(new and());
t.get_left().set_right_son_as_leaf(new or());
t.set_right_son(new and());
t.get_right().set_left_son_as_leaf(new or());
t.get_right().set_right_son_as_leaf(new or());
consumer.join();
t.calc_head_value(); //calc the head
System.out.println("The result is: " + t.head.value);
System.out.println();
/******************************
* compute with a single thread
********************************/
System.out.println("compute with a single thread");
int res = t.compute();
System.out.println("The result is: " + res);
/***********************************************
* printing a arithmatic expression of the tree
*************************************************/
System.out.println();
t.compute_with_print();
}
}
Consumer
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Consumer extends Thread {
Consumer() {
}
#Override
public void run() {
gate_node temp;
// the threads pool parts
ExecutorService executor = Executors.newFixedThreadPool(4);
try {
while ((temp = main_class.queue.take()).father_c != null) {
Runnable worker = new computingThread(temp);
executor.execute(worker);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
while (!executor.isTerminated()) {
}
}
}
computingThread
public class computingThread implements Runnable {
gate_node head;
int t_value;
public computingThread(gate_node head) {
this.head = head;
this.t_value = -1;
}
#Override
public void run() {
/* System.out.println("Start: "+this.hashCode()); */
t_value = head.op.calc(head.left_v,head.right_v);
/* System.out.println("thread: "+this.hashCode()+" is running ==> "+head.left_v+" "+head.op.toString()+" "+head.right_v+" = "+head.op.calc(head.left_v,head.right_v));
*/ head.value = this.t_value;
// update the father
if (head.isRightChild == true) { //update right fathers entire
head.father_c.right_v = t_value;
/*System.out.println("isRightChild");*/
} else { //update left fathers entire
head.father_c.left_v = t_value;
}
if ((head.father_c.right_v != -1) && (head.father_c.left_v != -1)){ //father is ready to compute-> to the queue!
try {
main_class.queue.put(head.father_c);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/* try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
/* System.out.println("thread: "+this.hashCode()+" is done!");
*/ return;
}
}
Here what I'm trying to do:
I'm trying to do a parllel comput that use multithreads to compute the finite value of the tree (each node gets two values, produce an outcome based on his opreator, pass it on the tree.. until the root is caculted). What I did is to set a queue of fixed number of spaces.
I insert the leafs to the queue as the tree is build. then I start a consumer that takes each leafs, caculate it, pass the result on the the right entrie of his father, and when both entreis are inserted into the father node, it also goes to the queue, and so on.. until the root is cacluted).
the only problem is that I cannot uses a queue that is smaller from the number of leafs in the tree, and I don't know why.
maybe becuase while I'm building the tree I'm inserting the leafs to the tree and if the queue is smaller then the leafs, I'm doing a: main_class.queue.put(this.right_c); when queue is already full, and that cause the progrem to wait until spaces on the queue will be freed which doesnt happen (cause I'm didn't start the threads yet).
Does anyone have any solution to that?
and another question? is that consider a parrlel computation? meaning if I set a queue with size 2, does that mean the I will do all the computation with only two threads (because I want to set is like the number of core CPU of a certain computer).
Thanks and sorry for my bad spelling.
I think you modelled it in a more complicated way than it was needed. I would not base my modelling on a tree. An electric circuit, is not always a tree. You could have more than one nodes acting as the circuits outputs, right?
I would base my modelling on the gate node. I would have a Gate class with two inputs and one output. Inputs and outputs, would be of type GateValue. Output would be calculated using a different way if the gate is an and or an or gate.
Then I would combine them building my circuit, like this:
gate1.Input1 = gate2.Output
gate1.Input2 = gate3.Output
etc.
Then, I would calculate the value of the last gate (output of the whole circuit) which would cause other gates to calculate their values. This way, you would not need a "parallel" calculation mechanism. As soon as you have no feedback loops in your circuit, this would work fine.
Hope I helped!
I'm writing code that will accept byte values from an arduino, store them as an array, preform some mathematical calculations, and then send the values back to the arduino. Right now I can send 127 values to the Arduino and I get 127 values back, but they are of type string, and any attempts to use the Integer class to convert these strings results in a program hang. I believe the buffer sometimes provides empty strings, and parseInt() doesn't know what to do. Does anyone have any suggestions? I'm very much a beginner in java and would be open to better solutions.
Here is my code:
package GridMap;
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 SerialWriter implements Runnable {
OutputStream out;
byte array[] = new byte[10];
byte c;
public SerialWriter(OutputStream out, byte[] in) {
this.out = out;
array = in;
}
public void run() {
try {
int index = 0;
c = array[index];
while ((c) > -1) {
this.out.write(c);
System.out.println("sent " + c);
if (index == 64){
Thread.sleep(2);
}
index++;
c = array[index];
}
TwoWaySerialComm.recieve();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
public class SerialReader implements Runnable {
static byte[] output = new byte[128];
private InputStream in;
private int[] buffer = new int[11];
static SerialPort thisSerialPort;
static OutputStream thisOut;
static String total = new String("333");
public SerialReader(InputStream in) {
this.in = in;
for (byte i = 0; i < 127; i++) {
output[i] = i;
}
output[127] = - 1;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
int index = 0;
int value;
try
{
Thread.sleep(200);
while (( len = this.in.read(buffer)) > -1 && index < 200)
{
String string = new String(buffer, 0, len);
//value = Integer.getInteger(string, len);
// System.out.print(value);
//System.out.println("buffer" + value);
System.out.print(string);
index++;
}
TwoWaySerialComm.send(output);
}
catch (Exception e )
{
e.printStackTrace();
}
}
public static int byteArrayToInt(byte[] b)
{
return b[3] & 0xFF |
(b[2] & 0xFF) << 8 |
(b[1] & 0xFF) << 16 |
(b[0] & 0xFF) << 24;
}
}
public class TwoWaySerialComm {
static SerialPort serialPort;
static OutputStream out = null;
static InputStream in;
static Thread receiveThread;
static Thread sendThread;
static byte[] output = new byte[11];
public TwoWaySerialComm() {
super();
}
void connect(String 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) commPort;
serialPort.setSerialPortParams(114400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
static void send(byte[] output) {
try {
out = serialPort.getOutputStream();
sendThread = new Thread(new SerialWriter(out, output));
sendThread.start();
//sendThread.join();
} catch (Exception e) {
System.out.println("Port Not Avaialable (send) ");
}
}
static void recieve(){
try {
in = serialPort.getInputStream();
receiveThread = new Thread(new SerialReader(in));
receiveThread.start();
receiveThread.join();
} catch (Exception e) {
}
}
public static void main(String[] args) {
try {
(new TwoWaySerialComm()).connect("COM3");
for (byte i = 0; i < 10; i++) {
output[i] = i;
}
output[10] = -1;
send(output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SerialPort returnSerialPort(){
return serialPort;
}
}
If you want get int from your stream, it is easier with a BuffereInputStream and use the read() method which return a int -> no conversion needed.
Add this in your SerialReader class :
Thread.sleep(200);
BufferedInputStream input = new BufferedInputStream(in);
while ((value = input.read()) != 1 && index < 200)
{
compute(value);
index++;
}
input.close();
Don't forget to close() your stream when you have read all the data. This is more important when you write, because if you don't close() not all data are written (except if you flush() before).
I did not quite get the description.
But the answer to the Title on the question is here.
Convert InputStream to byte array in Java
From corsiKa's answer to Determine if a String is an Integer in Java, you can check if a String is a valid int like this:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Having two InputStreams in Java, is there a way to merge them so you end with one InputStream that gives you the output of both streams? How?
As commented, it's not clear what you mean by merge.
Taking available input "randomly" from either is complicated by InputStream.available not necessarily giving you a useful answer and blocking behaviour of streams. You would need two threads to be reading from the streams and then passing back data through, say, java.io.Piped(In|Out)putStream (although those classes have issues). Alternatively for some types of stream it may be possible to use a different interface, for instance java.nio non-blocking channels.
If you want the full contents of the first input stream followed by the second: new java.io.SequenceInputStream(s1, s2).
java.io.SequenceInputStream might be what you need. It accepts an enumeration of streams, and will output the contents of the first stream, then the second, and so on until all streams are empty.
You can write a custom InputStream implementation that does this. Example:
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
public class CatInputStream extends InputStream {
private final Deque<InputStream> streams;
public CatInputStream(InputStream... streams) {
this.streams = new LinkedList<InputStream>();
Collections.addAll(this.streams, streams);
}
private void nextStream() throws IOException {
streams.removeFirst().close();
}
#Override
public int read() throws IOException {
int result = -1;
while (!streams.isEmpty()
&& (result = streams.getFirst().read()) == -1) {
nextStream();
}
return result;
}
#Override
public int read(byte b[], int off, int len) throws IOException {
int result = -1;
while (!streams.isEmpty()
&& (result = streams.getFirst().read(b, off, len)) == -1) {
nextStream();
}
return result;
}
#Override
public long skip(long n) throws IOException {
long skipped = 0L;
while (skipped < n && !streams.isEmpty()) {
int thisSkip = streams.getFirst().skip(n - skipped);
if (thisSkip > 0)
skipped += thisSkip;
else
nextStream();
}
return skipped;
}
#Override
public int available() throws IOException {
return streams.isEmpty() ? 0 : streams.getFirst().available();
}
#Override
public void close() throws IOException {
while (!streams.isEmpty())
nextStream();
}
}
This code isn't tested, so your mileage may vary.
Not that I can think of. You would probably have to read the contents of the two stream into a byte[] and then create a ByteArrayInputStream from that.
Here is an MVar implementation specific to byte arrays (make sure to add your own package definition). From here, it is trivial to write an input stream on merged streams. I can post that too if requested.
import java.nio.ByteBuffer;
public final class MVar {
private static enum State {
EMPTY, ONE, MANY
}
private final Object lock;
private State state;
private byte b;
private ByteBuffer bytes;
private int length;
public MVar() {
lock = new Object();
state = State.EMPTY;
}
public final void put(byte b) {
synchronized (lock) {
while (state != State.EMPTY) {
try {
lock.wait();
} catch (InterruptedException e) {}
}
this.b = b;
state = State.ONE;
lock.notifyAll();
}
}
public final void put(byte[] bytes, int offset, int length) {
if (length == 0) {
return;
}
synchronized (lock) {
while (state != State.EMPTY) {
try {
lock.wait();
} catch (InterruptedException e) {}
}
this.bytes = ByteBuffer.allocateDirect(length);
this.bytes.put(bytes, offset, length);
this.bytes.position(0);
this.length = length;
state = State.MANY;
lock.notifyAll();
}
}
public final byte take() {
synchronized (lock) {
while (state == State.EMPTY) {
try {
lock.wait();
} catch (InterruptedException e) {}
}
switch (state) {
case ONE: {
state = State.EMPTY;
byte b = this.b;
lock.notifyAll();
return b;
}
case MANY: {
byte b = bytes.get();
state = --length <= 0 ? State.EMPTY : State.MANY;
lock.notifyAll();
return b;
}
default:
throw new AssertionError();
}
}
}
public final int take(byte[] bytes, int offset, int length) {
if (length == 0) {
return 0;
}
synchronized (lock) {
while (state == State.EMPTY) {
try {
lock.wait();
} catch (InterruptedException e) {}
}
switch (state) {
case ONE:
bytes[offset] = b;
state = State.EMPTY;
lock.notifyAll();
return 1;
case MANY:
if (this.length > length) {
this.bytes.get(bytes, offset, length);
this.length = this.length - length;
synchronized (lock) {
lock.notifyAll();
}
return length;
}
this.bytes.get(bytes, offset, this.length);
this.bytes = null;
state = State.EMPTY;
length = this.length;
lock.notifyAll();
return length;
default:
throw new AssertionError();
}
}
}
}