Skip to content

Commit

Permalink
add support for message header to RAW CAN channels
Browse files Browse the repository at this point in the history
closes #5
  • Loading branch information
pschichtel committed Mar 9, 2024
1 parent cf859e7 commit b119222
Show file tree
Hide file tree
Showing 15 changed files with 443 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.time.Instant;

public class CanTestHelper {
public static final LinuxNetworkDevice CAN_INTERFACE = (LinuxNetworkDevice) lookupDev();
Expand Down Expand Up @@ -94,4 +95,8 @@ public static void runDelayed(Duration d, IORunnable r) {
public interface IORunnable {
void run() throws Exception;
}

public static Instant nowSeconds() {
return Instant.ofEpochSecond(Instant.now().getEpochSecond(), 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import static tel.schich.javacan.TestHelper.assertByteBufferEquals;
import static tel.schich.javacan.TestHelper.directBufferOf;
import static tel.schich.javacan.test.CanTestHelper.CAN_INTERFACE;
import static tel.schich.javacan.test.CanTestHelper.nowSeconds;

class J1939CanSocketTest {

Expand Down Expand Up @@ -115,7 +116,7 @@ void testReadMessage() throws Exception {
headerBuffer.setTimestamp(Instant.ofEpochSecond(headerBuffer.getTimestamp().getEpochSecond(), 0));
ImmutableJ1939ReceiveMessageHeader expected = new ImmutableJ1939ReceiveMessageHeader(
source,
Instant.ofEpochSecond(Instant.now().getEpochSecond(), 0),
nowSeconds(),
destination.getAddress(),
destination.getName(),
(byte) 6
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,12 @@
import tel.schich.javacan.CanFrame;
import tel.schich.javacan.JavaCAN;
import tel.schich.javacan.RawCanChannel;
import tel.schich.javacan.RawReceiveMessageHeaderBuffer;
import tel.schich.javacan.platform.linux.LinuxNativeOperationException;

import java.nio.ByteBuffer;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;

import static java.time.Duration.ofMillis;
Expand All @@ -40,6 +42,7 @@
import static tel.schich.javacan.CanFrame.*;
import static tel.schich.javacan.CanSocketOptions.*;
import static tel.schich.javacan.test.CanTestHelper.CAN_INTERFACE;
import static tel.schich.javacan.test.CanTestHelper.nowSeconds;

class RawCanSocketTest {

Expand Down Expand Up @@ -323,4 +326,26 @@ void testSendReadWriteReceiveCrossOver() throws Exception {
assertEquals(frame, received);
}
}

@Test
void testReceiveHeaders() throws Exception {
try (final RawCanChannel socket = CanChannels.newRawChannel()) {
socket.bind(CAN_INTERFACE);
socket.configureBlocking(true);
socket.setOption(RECV_OWN_MSGS, true);
socket.setOption(SO_RXQ_OVFL, true);
socket.setOption(SO_TIMESTAMP, true);

final CanFrame frame = CanFrame.create(0x7ED, FD_NO_FLAGS, new byte[] { 0x01 });
final ByteBuffer readBuffer = RawCanChannel.allocateSufficientMemory();
final RawReceiveMessageHeaderBuffer messageHeaderBuffer = new RawReceiveMessageHeaderBuffer();

socket.send(frame);
CanFrame received = socket.receive(readBuffer, messageHeaderBuffer);
assertEquals(frame, received);
assertEquals(CAN_INTERFACE, messageHeaderBuffer.getDevice());
assertEquals(0, messageHeaderBuffer.getDropCount());
assertEquals(Instant.now().getEpochSecond(), messageHeaderBuffer.getTimestamp().getEpochSecond());
}
}
}
18 changes: 9 additions & 9 deletions core/src/main/c/javacan_j1939.c
Original file line number Diff line number Diff line change
Expand Up @@ -174,17 +174,17 @@ JNIEXPORT jlong JNICALL Java_tel_schich_javacan_SocketCAN_receiveWithJ1939Header


struct iovec iov = {
.iov_base = buf,
.iov_len = (size_t) len,
.iov_base = buf,
.iov_len = (size_t) len,
};
struct msghdr header = {
.msg_name = &header_buffer->source_address,
.msg_namelen = sizeof(struct sockaddr_can),
.msg_control = control,
.msg_controllen = sizeof(control),
.msg_flags = 0,
.msg_iov = &iov,
.msg_iovlen = 1,
.msg_name = &header_buffer->source_address,
.msg_namelen = sizeof(struct sockaddr_can),
.msg_control = control,
.msg_controllen = sizeof(control),
.msg_flags = 0,
.msg_iov = &iov,
.msg_iovlen = 1,
};

ssize_t bytes_received = recvmsg(sock, &header, flags);
Expand Down
73 changes: 72 additions & 1 deletion core/src/main/c/javacan_raw.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@
#include "common.h"
#include <linux/can.h>
#include <linux/can/raw.h>
#include <sys/socket.h>
#include <asm-generic/socket.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stddef.h>

#define GET_FILTERS_DEFAULT_AMOUNT 10

Expand Down Expand Up @@ -168,4 +169,74 @@ JNIEXPORT jint JNICALL Java_tel_schich_javacan_SocketCAN_getErrorFilter(JNIEnv *
return result;
}
return mask;
}

struct raw_message_header_buffer {
struct sockaddr_can source_address;
jint drop_count;
jlong timestamp_seconds;
jlong timestamp_nanos;
};

JNIEXPORT jlong JNICALL Java_tel_schich_javacan_SocketCAN_receiveWithRawHeaders(JNIEnv *env, jclass clazz, jint sock, jobject buffer, jint offset, jint len, jint flags, jobject headerBuffer, jint headerOffset) {
void *raw_buf = (*env)->GetDirectBufferAddress(env, buffer);
void *buf = raw_buf + offset;
char control[200];

void *raw_header_buf = (*env)->GetDirectBufferAddress(env, headerBuffer);
struct raw_message_header_buffer* header_buffer = (struct raw_message_header_buffer*) (raw_header_buf + headerOffset);
memset(header_buffer, 0, sizeof(*header_buffer));
header_buffer->source_address.can_family = AF_CAN;

struct iovec iov = {
.iov_base = buf,
.iov_len = (size_t) len,
};
struct msghdr header = {
.msg_name = &header_buffer->source_address,
.msg_namelen = sizeof(struct sockaddr_can),
.msg_control = control,
.msg_controllen = sizeof(control),
.msg_flags = 0,
.msg_iov = &iov,
.msg_iovlen = 1,
};

ssize_t bytes_received = recvmsg(sock, &header, flags);
if (bytes_received == -1) {
throw_native_exception(env, "Unable to recvmsg from the socket");
return bytes_received;
}

for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&header); cmsg; cmsg = CMSG_NXTHDR(&header, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET) {
if (cmsg->cmsg_type == SO_RXQ_OVFL) {
memcpy(&header_buffer->drop_count, CMSG_DATA(cmsg), sizeof(__u32));
} else {
parse_timestamp(cmsg, &header_buffer->timestamp_seconds, &header_buffer->timestamp_nanos);
}
}
}

return bytes_received;
}

JNIEXPORT jint JNICALL Java_tel_schich_javacan_RawReceiveMessageHeaderBuffer_getStructSize(JNIEnv *env, jclass clazz) {
return sizeof(struct raw_message_header_buffer);
}

JNIEXPORT jint JNICALL Java_tel_schich_javacan_RawReceiveMessageHeaderBuffer_getStructDeviceIndexOffset(JNIEnv *env, jclass clazz) {
return offsetof(struct raw_message_header_buffer, source_address.can_ifindex);
}

JNIEXPORT jint JNICALL Java_tel_schich_javacan_RawReceiveMessageHeaderBuffer_getStructDropCountOffset(JNIEnv *env, jclass clazz) {
return offsetof(struct raw_message_header_buffer, drop_count);
}

JNIEXPORT jint JNICALL Java_tel_schich_javacan_RawReceiveMessageHeaderBuffer_getStructTimestampSecondsOffset(JNIEnv *env, jclass clazz) {
return offsetof(struct raw_message_header_buffer, timestamp_seconds);
}

JNIEXPORT jint JNICALL Java_tel_schich_javacan_RawReceiveMessageHeaderBuffer_getStructTimestampNanosOffset(JNIEnv *env, jclass clazz) {
return offsetof(struct raw_message_header_buffer, timestamp_nanos);
}
17 changes: 17 additions & 0 deletions core/src/main/c/javacan_socketcan.c
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
*/
#include "common.h"
#include <sys/socket.h>
#include <asm-generic/socket.h>
#include <unistd.h>
#include <poll.h>
#include <fcntl.h>
Expand Down Expand Up @@ -250,3 +251,19 @@ JNIEXPORT jboolean JNICALL Java_tel_schich_javacan_SocketCAN_getTimestampNsOptio
}
return result != 0;
}

JNIEXPORT jint JNICALL Java_tel_schich_javacan_SocketCAN_setReceiveQueueOverflow(JNIEnv *env, jclass clazz, jint sock, jboolean enable) {
jint result = set_boolean_opt(sock, SOL_SOCKET, SO_RXQ_OVFL, enable);
if (result == -1) {
throw_native_exception(env, "Unable to set receive queue overflow support");
}
return result;
}

JNIEXPORT jboolean JNICALL Java_tel_schich_javacan_SocketCAN_getReceiveQueueOverflow(JNIEnv *env, jclass clazz, jint sock) {
jint result = get_boolean_opt(sock, SOL_SOCKET, SO_RXQ_OVFL);
if (result == -1) {
throw_native_exception(env, "Unable to get receive queue overflow support");
}
return result != 0;
}
19 changes: 19 additions & 0 deletions core/src/main/java/tel/schich/javacan/CanSocketOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,25 @@ public TimestampingFlagSet get(int sock) throws IOException {
}
});

/**
* Option to enable the SO_RXQ_OVFL drop counter.
*
* @see <a href="https://man7.org/linux/man-pages/man2/setsockopt.2.html">setsockopt man page</a>
* @see <a href="https://man7.org/linux/man-pages/man2/getsockopt.2.html">getsockopt man page</a>
* @see <a href="https://man7.org/linux/man-pages/man7/socket.7.html">socket man page</a>
*/
public static final SocketOption<Boolean> SO_RXQ_OVFL = new CanSocketOption<>("SO_RXQ_OVFL", Boolean.class, new LinuxSocketOptionHandler<Boolean>() {
@Override
public void set(int sock, Boolean val, boolean validate) throws IOException {
SocketCAN.setReceiveQueueOverflow(sock, val);
}

@Override
public Boolean get(int sock) throws IOException {
return SocketCAN.getReceiveQueueOverflow(sock);
}
});

public enum TimestampingFlag {
TX_HARDWARE(1<<0),
TX_SOFTWARE(1<<1),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* The MIT License
* Copyright © 2018 Phillip Schichtel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package tel.schich.javacan;

import tel.schich.javacan.platform.linux.LinuxNetworkDevice;

import java.time.Instant;

public final class ImmutableRawReceiveMessageHeader implements RawReceiveMessageHeader {

private final LinuxNetworkDevice device;
private final int dropCount;
private final Instant timestamp;

public ImmutableRawReceiveMessageHeader(LinuxNetworkDevice device, int dropCount, Instant timestamp) {
this.device = device;
this.dropCount = dropCount;
this.timestamp = timestamp;
}

@Override
public LinuxNetworkDevice getDevice() {
return device;
}

@Override
public int getDropCount() {
return dropCount;
}

@Override
public Instant getTimestamp() {
return timestamp;
}

@Override
public ImmutableRawReceiveMessageHeader copy() {
return this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

import java.nio.ByteBuffer;

public class J1939AddressBuffer implements J1939Address {
public final class J1939AddressBuffer implements J1939Address {
public static final int BYTES;

private static final int DEVICE_INDEX_OFFSET;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@
import java.nio.ByteBuffer;
import java.time.Instant;

public class J1939ReceiveMessageHeaderBuffer implements J1939ReceiveMessageHeader {
public final class J1939ReceiveMessageHeaderBuffer implements J1939ReceiveMessageHeader {

static {
JavaCAN.initialize();
}

private static final int SOURCE_ADDRESS_OFFSET = getStructSourceAddressOffset();
private static final int TIMESTAMP_SECONDS_OFFSET = getStructTimestampSecondsOffset();
Expand Down
Loading

0 comments on commit b119222

Please sign in to comment.