From d0c9c0c02552136be3e5ca6251e62da02c689a99 Mon Sep 17 00:00:00 2001 From: Terekhin Alexander Date: Tue, 28 Apr 2026 14:22:58 +0300 Subject: [PATCH] Timestamp from socket via ioctl syscall Signed-off-by: Terekhin Alexander --- Makefile | 3 +-- can/can.go | 27 +++++++++++++++++++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index 060505f..0a52767 100644 --- a/Makefile +++ b/Makefile @@ -7,8 +7,7 @@ LDFLAGS = -ldflags "-s -w -buildid=$(git rev-parse HEAD)" all: clean test linux darwin windows linux: - GOOS=linux GOARCH=${GOARCH} go build ${LDFLAGS} -tags netgo -o ${BINARY}-linux-${GOARCH} . ; \ - cd - >/dev/null + GOOS=linux GOARCH=${GOARCH} go build ${LDFLAGS} -tags netgo -o ${BINARY}-linux-${GOARCH} . darwin: GOOS=darwin GOARCH=${GOARCH} go build ${LDFLAGS} -tags netgo -o ${BINARY}-darwin-${GOARCH} . ; \ diff --git a/can/can.go b/can/can.go index f3a7594..b5f76b5 100644 --- a/can/can.go +++ b/can/can.go @@ -60,23 +60,39 @@ func (sck *Socket) Bind(addr string, filter []unix.CanFilter) error { // Receive receives data from the CAN socket. // id is the CAN_frame id the data was originated from. -func (sck *Socket) Receive() (id uint32, data *[]byte, err error) { +func (sck *Socket) Receive() (id uint32, now time.Time, data *[]byte, err error) { var buf [frameSize]byte n, err := io.ReadFull(sck.dev, buf[:]) if err != nil { - return id, data, err + return id, time.Now(), data, err } if n != len(buf) { - return id, data, io.ErrUnexpectedEOF + return id, time.Now(), data, io.ErrUnexpectedEOF } + var tv unix.Timeval + + // Get timestamp + _, _, errno := unix.Syscall( + unix.SYS_IOCTL, + uintptr(sck.dev.fd), + uintptr(unix.SIOCGSTAMP), + uintptr(unsafe.Pointer(&tv)), + ) + + if errno != 0 { + return id, time.Now(), data, errors.New("Can't get timestamp") + } + + now = time.Unix(tv.Sec, tv.Usec*1000) + id = binary.LittleEndian.Uint32(buf[:4]) //TODO make correct switch betwin EFF and SFF id &= unix.CAN_EFF_MASK payload := make([]byte, buf[4]) copy(payload, buf[8:]) - return id, &payload, nil + return id, now, &payload, nil } // Send sends the provided frame on the CAN bus. @@ -134,8 +150,7 @@ func StartCan(fromBus chan<- *CanFrame, toBus <-chan *CanFrame, canbus string, f defer socket.Close() for { //TODO implement stop - if id, data, serr := socket.Receive(); serr == nil { - var now = time.Now() + if id, now, data, serr := socket.Receive(); serr == nil { fromBus <- &CanFrame{ Date: &now, CanId: id,