Send (Flush) Data to firmware using Usb Serial Port Android - java

I ve got an issue.
I want to send file from my android to a hardware.
But unfortunetely when the file has more than 10 kb , it seems some line of text are missing. Its doesnt send and write the file perfectly to my hardware when i check it. but if its less than, its seems working fine.
I have no much knowleges about micropython or similiar things like microcontroller stuff. But i think its regarding the way i write the data as byte are not quite faster might be the thing cause the issue.
Maybe some of you guys can solve my problem?
Maybe like an ampy functionality.
import com.felhr.usbserial.UsbSerialDevice;
private UsbSerialDevice serialPort
public void writeBytes(byte[] bytes) {
if (!usbServiceStarted) {
eventEmit(onErrorEvent, createError(com.melihyarikkaya.rnserialport.Definitions.ERROR_USB_SERVICE_NOT_STARTED, com.melihyarikkaya.rnserialport.Definitions.ERROR_USB_SERVICE_NOT_STARTED_MESSAGE));
return;
}
serialPort.write(bytes);
}
public void send (String content, boolean stop) {
int i = 0;
int step = 256;
byte[] command_bytes = content.getBytes(StandardCharsets.UTF_8);
===> probably starting from this line are the issue
while(i < command_bytes.length) {
int end = Math.min(i + step, command_bytes.length);
byte[] slice = Arrays.copyOfRange(command_bytes, i, end); ===> probably this is the issue
writeBytes(slice);
i += step;
}
if(stop) {
stop();
}
}

Related

huffman code - cant decompress BMP files using bitset

I built a classic Hoffman code, with encoder and decoder. I noticed that I had a problem, I use code in "bitset", to compress the input file. But the "bitset" - does not decode all the files I send to, for example when I send a txt file, it works great, but when I send other files like BMP. It doesn't work.
Before I used bitset - the code worked - but without any compression - so I'm afraid the problem is with bitset.
The decoder I built is:
public void Decompress(String[] input_names, String[] output_names) {
HuffmanVerticle tree = new HuffmanVerticle();
tree = readTreeFile(output_names);
restoreInput(tree, output_names, input_names);
}
public static void restoreInput(HuffmanVerticle tree, String[] binary_names, String[] original_names) {
BitSet huffmanCodeBit;
try {
FileOutputStream to_original = new FileOutputStream(original_names[0]);
FileInputStream binary = new FileInputStream(binary_names[0]);
ObjectInputStream s = new ObjectInputStream(binary);
huffmanCodeBit = (BitSet) s.readObject();
System.out.println(huffmanCodeBit.toString());
int index = 0;
while(huffmanCodeBit.length() > index)
{
HuffmanVerticle tmp = tree;
while (!tmp.isNullTree())
{
boolean bit = huffmanCodeBit.get(index);
index++;
System.out.println(bit);
if (!bit)
tmp = tmp.left;
else
tmp = tmp.right;
}
to_original.write(tmp.character);
}
binary.close();
to_original.close();
} catch (Exception e) {
e.printStackTrace();
}
}
What am I missing here? Why doesn't the code work for certain files? I'm trying to run the code on some files but it doesn't work, the files that come back don't work.
The code does not work for bmp files at all, even after half an hour, for example txt files, it runs very fast.
Thank for your help.

How do you light up the Arduino Mega diode using Java?

I would like to write a GUI in Java, in which there will be a button. Pressing the button will illuminate the diode connected to the Arduino. I'm using the RXTXcomm.jar library.
For now, I wrote code that displays the COM21 port because that's how my Arduino is connected to and opens it. Here's the code:
private String name;
private String portName;
private CommPortIdentifier portIdentifier = null;
private boolean staPort;
private void getPorts () throws PortInUseException {
List <String> list = new ArrayList ();
CommPortIdentifier serialPortId;
Enumeration enumComm;
enumComm = CommPortIdentifier.getPortIdentifiers ();
while (enumComm.hasMoreElements ()) {
serialPortId = (CommPortIdentifier) ​​enumComm.nextElement ();
name = serialPortId.getName ();
if ("COM21" .equals (name)) {
if (serialPortId.isCurrentlyOwned ()) {
System.out.println ("Port is open");
} Else {
serialPortId.open (name, WIDTH);
}
} else {
System.out.println ("error");
}
}
}
I would like to ask how to now ignite a diode connected to eg pin1? What method to use? I use an Arduino Mega. I found a few posts on this subject, unfortunately no specific answer matching my problem. I will be grateful for any help, materials or links.
Understand that you'll need two programs to do this. The first is similar to your Java program. But the second is the program that runs on the Arduino itself.
Here is a link that should give you an idea. The code is repeated below in case the link goes stale:
int led = 13; // Pin 13
void setup()
{
pinMode(led, OUTPUT); // Set pin 13 as digital out
// Start up serial connection
Serial.begin(9600); // baud rate
Serial.flush();
}
void loop()
{
String input = "";
// Read any serial input
while (Serial.available() > 0)
{
input += (char) Serial.read(); // Read in one char at a time
delay(5); // Delay for 5 ms so the next char has time to be received
}
if (input == "on")
{
digitalWrite(led, HIGH); // on
}
else if (input == "off")
{
digitalWrite(led, LOW); // off
}
}
This is the C code that needs to run on the Arduino. In this case, as you can see, it is using pin 13. You'll need to get an Arduino development environment setup to get this part working. See the Arduino Software page for information on how to setup the Arduino IDE. That will be different from your Netbeans IDE but the concepts are similar.
After you've got your sketch uploaded to your Arduino you'll connect to it at 9600 baud as shown in the Arduino code. Your Java code isn't setting communication parameters like baud rate so you'll need to update it for that. I found several links for setting the serial communication parameters in RXTX so take a look around.
Good luck - it seems like alot at first but it's really not too bad.

Using multiple ports to send images via two separate pair of Arducam and arduino Uno

I am trying to send images via two ports namely COM5 and COM7.
Following code does the most. Most significant part of the code is captureAndsaveImage method.
The problem is when i use both serial ports; images are getting distorted they feel like they are getting mixed up.
My question: Is it possible to use both port simaltaneously? What should i do such that there is no mixing up?
Don't mind second image's black circle it might have happened due to some signal losses in the second camera.
public class ReadPort {
private static final char[]COMMAND = {'*', 'R', 'D', 'Y', '*'};
private static final int WIDTH = 320; //640;
private static final int HEIGHT = 240; //480;
SerialPort serialPort,serialPort2;
public int[][] rgb2 = new int[WIDTH][HEIGHT];
public static void main(String[] args) {
ReadPort reader= new ReadPort();
}
public ReadPort() {
int[][]rgb = new int[HEIGHT][WIDTH];
try {
serialPort = SerialPort.getCommPort("COM7");
serialPort.openPort();
inputStream = serialPort.getInputStream();
serialPort.setComPortParameters(1000000,
8,
SerialPort.ONE_STOP_BIT,
SerialPort.NO_PARITY);
if(serialPort.isOpen()){
System.out.println("COM5 opened");
}
serialPort2 = SerialPort.getCommPort("COM5");
serialPort2.openPort();
inputStream2 = serialPort2.getInputStream();
serialPort2.setComPortParameters(1000000,
8,
SerialPort.ONE_STOP_BIT,
SerialPort.NO_PARITY);
if(serialPort2.isOpen()){
System.out.println("COM7 opened");
}
int counter = 0;
while(true) {
captureAndsaveImage( inputStream2,counter, rgb, "COM5");
captureAndsaveImage(inputStream, counter, rgb, "COM7");
counter++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void captureAndsaveImage(InputStream inputStream, int counter,int[][] rgb,String name) throws IOException{
while(!isImageStart(inputStream, 0)){};
System.out.print("Found image: " + counter);
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int temp =read(inputStream);
rgb[y][x] = ((temp&0xFF) << 16) | ((temp&0xFF) << 8) | (temp&0xFF);
}
}
BMP bmp = new BMP();
bmp.saveBMP("c:/out/" +name+"images/"+ counter + ".bmp", rgb);
System.out.println(", Saved image:"+name+"images/"+counter+".bmp");
}
private static int read(InputStream inputStream) throws IOException {
int temp = (char) inputStream.read();
//System.out.print(temp);
if (temp == -1) {
throw new IllegalStateException("Exit");
}
return temp;
}
private static boolean isImageStart(InputStream inputStream, int index) throws IOException {
if (index < COMMAND.length) {
if (COMMAND[index] == read(inputStream)) {
return isImageStart(inputStream, ++index);
} else {
return false;
}
}
return true;
}
}
Edit: I used a debug statement like
if(inputStream.available()>0){
System.out.println(inputStream.toString());}
in the captureAndsaveImage method and i got output like
COM5 opened
COM7 opened
Found image:
0com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#7f31245a
, Saved image:COM5images/0.bmp
Found image:
0com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/0.bmp
Found image:
1com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#7f31245a
, Saved image:COM5images/1.bmp
Found image:
1com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/1.bmp
Found image: 2, Saved image:COM5images/2.bmp
Found image:
2com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/2.bmp
Found image:
3com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#7f31245a
, Saved image:COM5images/3.bmp
Found image:
3com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/3.bmp
Found image: 4, Saved image:COM5images/4.bmp
Found image:
4com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/4.bmp
Found image:
5com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#7f31245a
, Saved image:COM5images/5.bmp
Found image:
5com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/5.bmp
Found image: 6, Saved image:COM5images/6.bmp
Found image: 6, Saved image:COM7images/6.bmp
Found image:
7com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#7f31245a
, Saved image:COM5images/7.bmp
Found image:
7com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/7.bmp
Found image: 8, Saved image:COM5images/8.bmp
Found image:
8com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/8.bmp
Found image:
9com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#7f31245a
, Saved image:COM5images/9.bmp
Things i observe is that some lines are like
Found image: 6, Saved image:COM5images/6.bmp
and most of them are
Found image:
5com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28
, Saved image:COM7images/5.bmp
What is the reason? As far as i know com.fazecast.jSerialComm.SerialPort$SerialPortInputStream#6d6f6e28 this is supposed to be address of the inputStream. But why it is not happening in some cases?
(I am beginner in Serial communication.)
Hurray! I have solved my problem. Even though solution isn't elegant.
I put a block of code in the start of captureAndsaveImage method like
while(inputStream.available()>0){
int temp=read(inputStream);
}
And now I am getting cleared image. I have some vague idea how it worked
but i would love if anyone can give logic for these.
Edit: I observe that distorted images were coming in odd frames. So the above code just skips those frames shows even frames which are not mixed up. :/
Your code seems to be very disorganized. For example, where you open COM5, your debug messages says it's opening COM7 and vice versa.
However, the bug causing the issue you raised in your question is with these lines of code:
while(true) {
captureAndsaveImage( inputStream2,counter, rgb, "COM5");
captureAndsaveImage(inputStream, counter, rgb, "COM7");
counter++;
}
As you can see, you're storing the data from both image sources into the same array, rgb. Your code has an rgb2, so I suspect you meant to use one of those with COM5 and the other for COM7, though the array declarations being at different scopes is strange. I would suggest you review your code, and perhaps focus on getting things working with one serial port/data source before introducing a second.
Edit: reading your comment and reviewing your error, I found another bug:
private static boolean isImageStart(InputStream inputStream, int index) throws IOException {
if (index < COMMAND.length) {
if (COMMAND[index] == read(inputStream)) {
return isImageStart(inputStream, ++index);
}
else {
return false;
}
}
return true;
}
Here, isImageStart() could return true if it works out that you missed the starting character in a stream. Essentially, since you recursively call isImageStart, if you start with a stream that doesn't contain the command character, you will run until you reach COMMAND.length, at which point, the next recursive call would skip the if (index < COMMAND.length) and return true. So, if you have a case where you started reading too soon (or too late), isImageStart() will still return true. Then, in CaptureAndSaveImage(), you still continue calling read on the inputstream and likely are reading stale data from the previous stream. Except by that point, the stream may be valid and depending on how fast data is coming in, you will have a mix of the previous image and the one currently being received.

JnetPcap: reading from offline file very slow

I'm building a sort of custom version of wireshark with jnetpcap v1.4r1425. I just want to open offline pcap files and display them in my tableview, which works great except for the speed.
The files I open are around 100mb with 700k packages.
public ObservableList<Frame> readOfflineFiles1(int numFrames) {
ObservableList<Frame> frameData = FXCollections.observableArrayList();
if (numFrames == 0){
numFrames = Pcap.LOOP_INFINITE;
}
final StringBuilder errbuf = new StringBuilder();
final Pcap pcap = Pcap.openOffline(FileAddress, errbuf);
if (pcap == null) {
System.err.println(errbuf); // Error is stored in errbuf if any
return null;
}
JPacketHandler<StringBuilder> packetHandler = new JPacketHandler<StringBuilder>() {
public void nextPacket(JPacket packet, StringBuilder errbuf) {
if (packet.hasHeader(ip)){
sourceIpRaw = ip.source();
destinationIpRaw = ip.destination();
sourceIp = org.jnetpcap.packet.format.FormatUtils.ip(sourceIpRaw);
destinationIp = org.jnetpcap.packet.format.FormatUtils.ip(destinationIpRaw);
}
if (packet.hasHeader(tcp)){
protocol = tcp.getName();
length = tcp.size();
int payloadOffset = tcp.getOffset() + tcp.size();
int payloadLength = tcp.getPayloadLength();
buffer.peer(packet, payloadOffset, payloadLength); // No copies, by native reference
info = buffer.toHexdump();
} else if (packet.hasHeader(udp)){
protocol = udp.getName();
length = udp.size();
int payloadOffset = udp.getOffset() + udp.size();
int payloadLength = udp.getPayloadLength();
buffer.peer(packet, payloadOffset, payloadLength); // No copies, by native reference
info = buffer.toHexdump();
}
if (packet.hasHeader(payload)){
infoRaw = payload.getPayload();
length = payload.size();
}
frameData.add(new Frame(packet.getCaptureHeader().timestampInMillis(), sourceIp, destinationIp, protocol, length, info ));
//System.out.print(i+"\n");
//i=i+1;
}
};
pcap.loop(numFrames, packetHandler , errbuf);
pcap.close();
return frameData;
}
This code is very fast for the first maybe 400k packages, but after that it slows down a lot. It needs around 1 minute for the first 400k packages and around 10 minutes for the rest. What is the issue here?
It's not that the list is getting too timeconsuming to work with is it? the listmethod add is O(1), isnt it?
I asked about this on the official jnetpcap forums too but it's not very active.
edit:
turn out it slows down massively because of the heap usage. Is there a way to reduce this?
As the profiler showed you, you're running low on memory and it starts to slow down.
Either give more memory with -Xmx or don't load all the packets into memory at once.

Bluetooth Serial Data Transfer Hangs at same points

I am to transfer two files from a Java app to an Arduino of roughly 200k each to be saved to uSD. With a USB connection this is going fine using the RXTX library and simple data parsing on the Arduino. I now want to replace the USB connect with a bluetooth using a HC-06 module.
Without changing anything the transfer works but it takes 12 minutes rather than 2 minutes. The transfer hangs at the same 4 (maybe 50) points of the transfer, seen by percentage progress.
The bottleneck must be in the RXTX library or bluteooth TX but can't find what's happening. Is there anything I can tweak or is this a limitation of a basic bluetooth module?
Here are snippets from code FWIW, nothing out of the ordinary (I think!) :
Java :
int perc = data.length / 100;
for (int i = 0 ; i < data.length ; i++) {
try{
output.write(data[i]);
}
catch(Exception e){
System.err.println(e.toString());
}
if(i % perc == 0) System.out.println(i / perc);
}
Arduino :
boolean waiting = true;
while( lastData + 2000 > millis() || waiting){
while(Serial.available()) {
waiting = false;
if(Serial.available() >= 255) nodes[nodeCount++] = byteCount;
buff[bytInc++] = Serial.read();
if(bytInc == 512) {
bytInc = 0;
in.write(buff,512);
}
lastData = millis();
byteCount++;
}
}
in.write(buff,bytInc);
in.flush();
Any optimisation in the snippets above would be much appreciated. The baud rate is 38400. Any faster and the buffer overloads when writing to uSD.
Arduino board is a Mega with 256 byte serial buffer.
Much appreciated. Have hunted about for relevant posts but can't find anything on bluetooth file transfers like this.

Categories

Resources