Skip to content

Commit

Permalink
Vectronix Terrapin-X laser rangefinder protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
platypii committed Oct 27, 2024
1 parent 1d830c4 commit c1a4aed
Show file tree
Hide file tree
Showing 4 changed files with 438 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.platypii.baseline.lasers.rangefinder;

class Crc16 {
/**
* Computes the CRC16 checksum for a given byte array.
*/
public static short crc16(byte[] byteArray) {
int crc = 0xffff;

// Process bytes in pairs (LSB first)
for (int i = 0; i < byteArray.length; i++) {
int b = byteArray[i] & 0xff;
crc ^= b;

// Process each bit
for (int j = 0; j < 8; j++) {
if ((crc & 0x0001) != 0) {
crc = (crc >> 1) ^ 0x8408; // 0x8408 is reversed polynomial
} else {
crc = crc >> 1;
}
}
}

// XOR with 0xfff
crc ^= 0xffff;

return (short) crc;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public class RangefinderService {
private final BleProtocol protocols[] = {
new ATNProtocol(),
new SigSauerProtocol(),
new TerrapinProtocol(),
new UineyeProtocol()
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.platypii.baseline.lasers.rangefinder;

import android.util.Log;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

// Sentences start with 7e and end with 7e
// Sometimes 1 sentence takes 2 messages
// Sometimes 2 sentences come in 1 message
class TerraSentenceIterator implements Iterator<byte[]> {
private static final String TAG = "TerraSentenceIterator";

@NonNull
private final List<Byte> byteBuffer = new ArrayList<>();

// Sentences ready to read
@NonNull
private final List<byte[]> sentences = new ArrayList<>();

private int state = 0;

void addBytes(@NonNull byte[] bytes) {
for (byte b : bytes) {
addByte(b);
}
}

private void addByte(byte b) {
byteBuffer.add(b);
if (state == 0) {
if (b == 0x7e) state = 1;
else Log.e(TAG, "missing preamble");
} else if (state == 1) {
if (b == 0x7e) {
addSentence();
state = 0;
}
}
}

private void addSentence() {
byte[] sent = new byte[byteBuffer.size() - 2];
for (int i = 0; i < byteBuffer.size() - 2; i++) {
sent[i] = byteBuffer.get(i + 1);
}
sentences.add(sent);
byteBuffer.clear();
}

@Override
public boolean hasNext() {
return !sentences.isEmpty();
}

@Override
public byte[] next() {
return sentences.remove(0);
}

@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
Loading

0 comments on commit c1a4aed

Please sign in to comment.