I'm trying to send data from Raspberry PI to Arduino via I2c.
When i execute the code with a stand alone java application i'm able to send and receive data with NO problem (the code bellow is giving me the expected result).
public static void main(String[] args) throws Exception {
// get I2C bus instance
final I2CBus bus = I2CFactory.getInstance(I2CBus.BUS_1);
I2CDevice arduino = bus.getDevice(0x04);
byte[] buffer = new byte[1];
buffer[0] = 1;
arduino.write(buffer, 0, buffer.length);
Thread.sleep(100);
buffer[0] = 0;
int number = arduino.read(buffer, 0, 1);
}
Then i try the same code, but this time it is inside a Servlet, using Jetty in the Raspberry Pi, and i get the following error:
java.io.IOException: Cannot open file handle for /dev/i2c-1 got -1 back.
at com.pi4j.io.i2c.impl.I2CBusImpl.<init>(I2CBusImpl.java:96)
at com.pi4j.io.i2c.impl.I2CBusImpl.getBus(I2CBusImpl.java:70)
at com.pi4j.io.i2c.I2CFactory.getInstance(I2CFactory.java:56)..
Does anyone know what may be happening?
Regards,
Could it be that in one case your process has sudo rights and it doesn't in the other case?
The answer is
I2CFactory.getInstance(I2CBus.BUS_0);
in some cases, the BUS is inverted so try this, i hope it helps :)
Related
I am attempting to make a player appear like they are sneaking (crouching) on Minecraft 1.8.8 running Spigot, based on http://wiki.vg/Entities#Entity_Metadata_Format I have done the following:
Created a data watcher and mapped appropriate value for crouched from the wiki:
DataWatcher dw = new DataWatcher(null);
dw.a(0, (byte) 0x02);
Created the packet, where target is a Player object of the player that needs to appear sneaking:
PacketPlayOutEntityMetadata metadataPacket = new PacketPlayOutEntityMetadata(target.getEntityId(), dw, false);
Sent the packet to everyone online:
for (Player p : Bukkit.getOnlinePlayers()) {
((CraftPlayer) p).getHandle().playerConnection.sendPacket(metadataPacket);
}
This does not appear to be working though, how would be the appropriate way to go about this?
I attempted to use ProtocolLib too, though ideally I am looking for a solution that works using packets.
The problem is that you use the wrong method for updating. There is a internal boolean in the datawatcher that checks for updates. There are 2 ways solving this problem.
Using DataWatcher#watch:
Player target = Bukkit.getPlayer("RandomGuy");
DataWatcher dw = ((CraftPlayer) target).getHandle().getDataWatcher();
dw.watch(0, (byte) 2);
PacketPlayOutEntityMetadata metadataPacket = new PacketPlayOutEntityMetadata(target.getEntityId(), dw, false);
//sending packet...
Skipping the internal boolean (not recommended):
Player target = Bukkit.getPlayer("RandomGuy");
DataWatcher dw = ((CraftPlayer) target).getHandle().getDataWatcher();
dw.a(0, (byte) 2);
PacketPlayOutEntityMetadata metadataPacket = new PacketPlayOutEntityMetadata(target.getEntityId(), dw, true);
//sending packet...
P.S. If that is a fake entity, I'd recommend instantiating a reference of an EntityPlayer for better packet control.
I'm trying to send in-memory data as a file to remote server by using org.apache.sshd.client.
My code so far:
// Connect to remote server code
sftp = session.createSftpClient();
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 1000; j++) {
sb.append("a");
}
byte[] data = sb.toString().getBytes(StandardCharsets.UTF_8);
sftp.write(h, 0, data, 0, data.length);
Every things are fine until i try to make my input data bigger.
I set loop count from 1000 to 1000000.
And it's keep throwing following exception:
org.apache.sshd.common.SshException: Channel has been closed
.
I try to set SFTP's [channel open timeout] more bigger but can not resolve this problem.
So I realized that any time data size greater than 256KB, the exception will be thrown. I tried to edit IO Buffer size, Write buffer, Read buffer but the problem is still there.
Is there any way to setting data size or any way to solve this problem? Thanks you all in advance.
I am trying to create a Java obd2 scanner app for my mitsubishi lancer mx 1997 which use MUTII protocol over OBD2. Can anybody help me to read MUT request codes using jd2xx library.
I have tried the below program, but it didn read engine RPM.
package lancerscan;
import jd2xx.JD2XX;
public class Test2 {
public static void main(String[] args) throws Exception {
JD2XX jd = new JD2XX();
jd.open(0);
jd.setBaudRate(38400);
jd.setDataCharacteristics(
8, JD2XX.STOP_BITS_1, JD2XX.PARITY_NONE);
jd.setFlowControl(
JD2XX.FLOW_NONE, 0, 0);
jd.setTimeouts(1000, 1000);
String msg = "21";
int ret = jd.write(msg.getBytes());
System.out.println(ret + " bytes sent.");
int rd = jd.read();
System.out.println(">>>" + rd);
int status = jd.getQueueStatus();
byte[] data = new byte[(int) status];
long lngBytesReturned = jd.read(data, 0, data.length);
System.out.println("======= " + lngBytesReturned);
}
}
MUT request code for Engine RPM is 0x21
more MUT request codes can be found here
similar C programs which works fine is here; main prjct files are here
Thanks,
harsha
First your using a different baud rate to that in the example. The example uses 15625 baud but you are using 38400 baud.
Secondly you are missing some of the setup commands. I am not sure if this will make a difference but its something that is different between your code and the example.
Mitsubishi require you to set the car ECU into diagnostic mode by sending 0x00 at a rate of 5 baud on one of the pins. On the OpenPort 1.3D cable this translates to setting the break to on for 1800 ms and then turning it off. You can see this is done with the ftdimut_init() command from the libftdimut.c file.
printf("Sending 0x00 at 5 baud\n");
printf("Break on......\n");
ftStatus = FT_SetBreakOn(ftdimut_ftHandle);
if(ftStatus != FT_OK) return ftStatus;
ftdimut_msleep(1800);
printf("Break off......\n");
ftStatus = FT_SetBreakOff(ftdimut_ftHandle);
if(ftStatus != FT_OK) return ftStatus;
The car ECU will then send you 4 bytes containing the ECU ID. This can then be used to check the ECU correctly entered diagnostic mode. You can see this in libftdimut.c.
ftStatus = FT_Read(ftdimut_ftHandle, buf, 4, &bytesRead);
if(ftStatus != FT_OK) return ftStatus;
if(bytesRead == 4) {
return FT_OK;
}
Now assuming that you got the 4 bytes back you can start to send the diagnostic codes such as 0x17 or 0x21.
I just saw your post on my blog, niallm answer is correct, you need to do a 5 baud init first which involves driving the KLine, you can use something like the 5 baud init posted in that answer, more info about the protocol:
http://evoecu.logic.net/wiki/MUT_Protocol
After getting a 4 byte response you can start sending requests at 15625 baud (I'm communicating with a 94 3000GT so the CEL light stops blinking), also in my case I send the converted values (0x21 = 33 decimal) as a byte array.
How can I convert integer values to byte arrays and then send them over a byte stream to the client program which converts the byte array back to an integer?
My program is a pingpong game. Once run it creates a server which a client connects to over the internet using an object stream right now. All is working well, but it doesn't seem very efficient. By that I mean the ball is stuttering back and forth while it is trying to keep in sync via the update loop. I may have programmed it loosely, but it was the best I could come up with. I hope someone who knows a lot more about how this kind of thing works can help me clear some things up.
My question put straight. I need to know a better way to send the ball positions and player position over the internet more efficiently. Currently the time it takes is too long. Although, I could be updating it the wrong way.
The way the streams are constructed:
oostream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
oostream.flush();
oistream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
This is player 2's update loop:
IntData id = new IntData();
while (running) {
id.ballx = ballx;
id.bally = bally;
id.player2Y = player2Y;
oostream.writeObject(id);
oostream.flush();
Thread.sleep(updaterate);
id = (IntData) oistream.readObject();
player1Y = id.player1Y;
ballx = id.ballx;
bally = id.bally;
}
Player 1 is the server host.
This is player 1's update loop:
IntData id = new IntData();
while (running) {
id = (IntData) oistream.readObject();
player2Y = id.player2Y;
ballx = id.ballx;
bally = id.bally;
Thread.sleep(updaterate);
id.ballx = ballx;
id.bally = bally;
id.player1Y = player1Y;
oostream.writeObject(id);
oostream.flush();
}
I suggest not using full serialization for simply primitives. use DataInputStream and the like instead:
dostream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
distream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
Then read with:
ballx=distream.readInt();
bally=distream.readInt();
and write as:
dostream.writeInt(ballx);
dostream.writeInt(bally);
Also I suggest you not sleep awaiting data on both sides. Sleep on one and let the second simply await for a full set of data before transmitting by cutting out the Thread.sleep() there.
this is the function im using everytime for it
its pretty simple and works perfectly but the function is not rly needed (just very easy to use)
public static final byte[] parseIntToByteArray(int i){
byte[] b = {(byte)(i >> 24),
(byte)(i >> 16),
(byte)(i >> 8),
(byte)i};
return b;
}
to get it back:
int xy = (bytearray[0] << 24 | bytearray[1] << 16 | bytearray[2] << 8 | bytearray[3]);
Have some problems with JNetPcap.
I uses Ubuntu 12.04, and trying to make packet snipper that based in java language.
What I did is below.
I have downloaded JNetPcap 1.3.0.
And as tutorial said built a java project.
http://jnetpcap.com/examples/dumper <- this is the link.
I typed just like that link and I got my first problem.
PcapHandler Class is deprecated. So I find the document and replace it with ByteBufferHandler.
Now I compile this project and got an unsatifiedLinked Error.
I have tried with static block to load that library.
After some attempts I copied "libjnetpcap.so" to /usr/lib/
now I remove unsatisfiedLinked Error. but somehow it stops in 1st Error check.
It prints "1st error check : ", then exit automatically.
public static void main(String[] args) {
List<PcapIf> alldevs = new ArrayList<PcapIf>();
StringBuilder errbuff = new StringBuilder();
int r = Pcap.findAllDevs(alldevs, errbuff);
//============1st check
if(r == Pcap.NOT_OK || alldevs.isEmpty()){
System.err.printf("1st error check : %s\n", errbuff.toString());
return;
}
PcapIf device = alldevs.get(1);
//===================== END
int snaplen = 64 * 1024;
int flags = Pcap.MODE_PROMISCUOUS;
int timeout = 10 * 1000;
Pcap pcap = Pcap.openLive(device.getName(),snaplen, flags, timeout, errbuff);
//============2nd check
if(pcap == null){
System.err.printf("2nd error check : %s\n", errbuff.toString());
return;
}
//===================== END
String ofile = "/home/juneyoungoh/tmp_capture_file.cap";
final PcapDumper dumper = pcap.dumpOpen(ofile);
ByteBufferHandler<PcapDumper> handler = new ByteBufferHandler<PcapDumper>() {
#Override
public void nextPacket(PcapHeader arg0, ByteBuffer arg1, PcapDumper arg2) {
dumper.dump(arg0, arg1);
}
};
pcap.loop(10,handler, dumper);
File file = new File(ofile);
System.out.printf("%s file has %d bytes in it!\n", ofile, file.length());
dumper.close();
pcap.close();
if(file.exists()){
file.delete();
}
}
if is there any good reference or wonderful idea, please share.
Thanks.
On Linux, a program will probably have to run as root, or with sufficient privileges granted in some other fashion, in order to be able to open any devices, and, currently, pcap_findalldevs(), which is presumably what the Pcap.findAllDevs method uses, tries to open each of the devices it finds, and only returns the devices it can open.
So you'll have to run your Java program as root, or will somehow have to arrange that it have sufficient privileges (CAP_NET_RAW and CAP_NET_ADMIN) to get a list of network adapters and open those adapters.