12 Commits
Author SHA1 Message Date
esilva 34f14e8dc0 Fix a bug. The recorder was writing out the buffer instead of the OG data 2026-07-01 09:34:38 +01:00
esilva 52056a7da3 updated it to use the latest and greatest API change on bngsdk
May have introduce some stupid things, will look at them after
2026-07-01 00:20:12 +01:00
esilva 31a2f85407 added a view to the recording utility of BeamNG too 2026-06-29 11:27:27 +01:00
esilva b8d915af4f print the error when it throws an error
it might not even matter because it will just flash too fast
2026-06-29 11:23:12 +01:00
esilva 99b3891c60 Moved the outgauge data prints to a standalone function 2026-06-29 00:19:57 +01:00
esilva 988124ef60 Alignement 2026-06-26 18:00:40 +01:00
esilva 422e8fcdc2 very simple way of visualizing the data flowing 2026-06-26 17:49:15 +01:00
esilva 7c558eda9c Change the recorder to save data in the binary format replay reads 2026-06-26 11:32:37 +01:00
esilva c23c39d889 Performance and API improvements for the replay function 2026-06-26 11:31:46 +01:00
esilva 7939f07f34 benchmark file 2026-06-25 23:02:42 +01:00
esilva 4d05e636b6 Laying the groundwork for a better view of the output 2026-06-25 22:45:25 +01:00
esilva 540cb90f42 Updated the README 2025-10-14 18:33:12 +01:00
11 changed files with 480 additions and 68 deletions
+1
View File
@@ -1 +1,2 @@
*.bin
*.work*
+35 -1
View File
@@ -12,7 +12,41 @@ without having to be playing the game while doing it (fans are noisy).
# Usage
To start replaying:
`BeamNGMockOg replay -a 127.0.0.1 -p 4443 -i sunburstManual.bin`
`BeamNGMockOg replay [--loop] -a 127.0.0.1 -p 4443 -i sunburstManual.bin`
- `loop` allows the replay functionality to keep replaying the same data file
To start recording:
`BeamNGMockOg record -a 127.0.0.1 -p 4443 -o sunburstDCT.bin`
## Development
Use `tcpdump` to listen to the socket and check if data is coming through:
`tcpdump -i any udp port <port> -X`
### Benchmark
Run with:
`go test ./mockserver -bench=BenchmarkReplayAsync -benchmem -benchtime=1x -memprofile=mem.pprof`
Analyze the output with:
`go tool pprof -sample_index=alloc_objects mem.pprof` -> `top`
- `ignore=net` will ignore the net package for example
- `focus=mockserver` will show only the results from this code we are testing
or
`go tool pprof -http=:8080 mem.pprof`
#### Previous results:
goos: linux
goarch: amd64
pkg: github.com/ESilva15/BeamNGMockOg/mockserver
cpu: AMD Ryzen 5 5600G with Radeon Graphics
BenchmarkReplayAsync-12 1 109433574741 ns/op 4533008 B/op 66059 allocs/op
PASS
ok github.com/ESilva15/BeamNGMockOg/mockserver 109.438s
#### Current results
goos: linux
goarch: amd64
pkg: github.com/ESilva15/BeamNGMockOg/mockserver
cpu: AMD Ryzen 5 5600G with Radeon Graphics
BenchmarkReplayAsync-12 1 109433931841 ns/op 356088 B/op 13272 allocs/op
PASS
ok github.com/ESilva15/BeamNGMockOg/mockserver 109.440s
+10 -1
View File
@@ -1,6 +1,7 @@
package cmd
import (
"context"
"fmt"
"github.com/ESilva15/BeamNGMockOg/mockserver"
@@ -13,7 +14,15 @@ func recordAction(cmd *cobra.Command, args []string) {
address, _ := cmd.Flags().GetString("address")
port, _ := cmd.Flags().GetInt("port")
if err := mockserver.Record(address, port, outputFile); err != nil {
recorder, err := mockserver.NewRecorder(outputFile, address, port)
if err != nil {
panic(fmt.Sprintf("failed to create new BeamNG recorder: %+v", err))
}
defer recorder.Close()
// NOTE: is this doing anything at all??
ctx := context.Background()
if err := recorder.Record(ctx); err != nil {
fmt.Printf("Something went wrong while recording the file: %v", err)
}
}
+8 -1
View File
@@ -15,8 +15,15 @@ func replayAction(cmd *cobra.Command, args []string) {
port, _ := cmd.Flags().GetInt("port")
loop, _ := cmd.Flags().GetBool("loop")
replayer, err := mockserver.NewReplayer(address, port, inputFile)
if err != nil {
fmt.Printf("Something went wrong setting up the player: %+v", err)
return
}
// NOTE: is this doing anything at all??
ctx := context.Background()
if err := mockserver.Replay(ctx, address, port, loop, inputFile); err != nil {
if err := replayer.Replay(ctx, loop); err != nil {
fmt.Printf("Something went wrong while playing the file: %v", err)
}
}
+1 -3
View File
@@ -1,11 +1,9 @@
module github.com/ESilva15/BeamNGMockOg
replace github.com/ESilva15/gobngsdk => ../pkg/bngsdk
go 1.23.2
require (
github.com/ESilva15/gobngsdk v0.0.0-00010101000000-000000000000
github.com/ESilva15/gobngsdk v1.1.1
github.com/spf13/cobra v1.10.1
)
+2 -2
View File
@@ -1,5 +1,5 @@
github.com/ESilva15/gobngsdk v0.0.2 h1:N6stNOE14Wg80BAZMFu/Qd9Qa/J0DmExCfdPoDf7lco=
github.com/ESilva15/gobngsdk v0.0.2/go.mod h1:cKLaZRgM0tGGXDvosaSjHnxeyC5Y6rg7zCLqEUJnOzw=
github.com/ESilva15/gobngsdk v1.1.1 h1:MyKUjIqG77lYcUY6cnZpnnxPoxS/FdAYwGoi6InXan0=
github.com/ESilva15/gobngsdk v1.1.1/go.mod h1:cKLaZRgM0tGGXDvosaSjHnxeyC5Y6rg7zCLqEUJnOzw=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+10 -20
View File
@@ -1,25 +1,23 @@
package mockserver
import (
"bytes"
"encoding/binary"
"encoding/gob"
"io"
"unsafe"
sdk "github.com/ESilva15/gobngsdk"
)
type GobReader struct {
TotalRead int
TotalRead int64
File io.ReadSeeker
Dec *gob.Decoder
Buf []byte
}
func NewGobReader(r io.ReadSeeker) *GobReader {
return &GobReader{
TotalRead: 0,
File: r,
Dec: gob.NewDecoder(r),
Buf: make([]byte, unsafe.Sizeof(sdk.Outgauge{})),
}
}
@@ -29,27 +27,19 @@ func (g *GobReader) Reset() error {
return err
}
g.Dec = gob.NewDecoder(g.File)
g.TotalRead = 0
return nil
}
func (g *GobReader) Next() ([]byte, error) {
var og sdk.Outgauge
err := g.Dec.Decode(&og)
func (g *GobReader) Next(buffer []byte) error {
_, err := io.ReadFull(g.File, buffer)
if err != nil {
return nil, err
return err
}
buf := new(bytes.Buffer)
err = binary.Write(buf, binary.LittleEndian, &og)
if err != nil {
return nil, err
}
pos, _ := g.File.Seek(0, io.SeekCurrent)
g.TotalRead = pos
g.TotalRead += len(buf.Bytes())
return buf.Bytes(), nil
return nil
}
+123 -23
View File
@@ -1,41 +1,141 @@
package mockserver
import (
"encoding/gob"
"log"
"context"
"encoding/binary"
"fmt"
"os"
"strings"
"sync"
"time"
bngsdk "github.com/ESilva15/gobngsdk"
)
type recorderViewData struct {
TotalBytes int
SDK *bngsdk.BeamNGSDK
}
type Recorder struct {
SDK bngsdk.BeamNGSDK
OutputFile *os.File
TotalBytes int
// Views
mut sync.RWMutex
viewDataMut sync.RWMutex
viewData recorderViewData
viewCh chan *recorderViewData
recorderCh chan []byte
}
func NewRecorder(fp string, address string, port int) (*Recorder, error) {
var recorder Recorder
var err error
recorder.SDK, err = bngsdk.Init(address, port)
if err != nil {
return &Recorder{}, err
}
recorder.OutputFile, err = os.Create(fp)
if err != nil {
return &Recorder{}, err
}
recorder.viewData = recorderViewData{}
recorder.viewCh = make(chan *recorderViewData, 1)
recorder.recorderCh = make(chan []byte, 1)
return &recorder, nil
}
func (r *Recorder) Close() {
r.SDK.Close()
if r.OutputFile != nil {
r.OutputFile.Close()
}
}
func (r *Recorder) record(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case data := <-r.recorderCh:
r.mut.Lock()
err := binary.Write(r.OutputFile, binary.LittleEndian, r.SDK.Data)
r.TotalBytes += len(data)
r.mut.Unlock()
if err != nil {
// NOTE: find a way of logging this somehow
}
}
}
}
func (r *Recorder) view(ctx context.Context) {
var s strings.Builder
var nBytes int
for {
select {
case <-ctx.Done():
return
case viewData := <-r.viewCh:
s.Reset()
fmt.Fprintf(os.Stdout, "\x1b[2J\x1b[H")
stringifyRecordingProgress(&s, nBytes)
fmt.Fprintf(&s, "\n\n")
r.viewDataMut.RLock()
nBytes = viewData.TotalBytes
stringifyOutgaugeData(&s, &r.SDK)
r.viewDataMut.RUnlock()
fmt.Fprint(os.Stdout, s.String())
}
}
}
// Record records data from the UDP connection created by address and port
func Record(address string, port int, filePath string) error {
func (r *Recorder) Record(ctx context.Context) error {
ticker := time.NewTicker(time.Second / 60)
defer ticker.Stop()
// Create the output file
bin, err := os.Create(filePath)
if err != nil {
return err
}
go r.record(ctx)
go r.view(ctx)
// Create the BeamNGSDK instance
beam, err := bngsdk.Init(address, port)
if err != nil {
return err
}
defer beam.Close()
enc := gob.NewEncoder(bin)
for {
err := beam.ReadData()
if err != nil {
return err
select {
case <-ctx.Done():
return nil
case <-ticker.C:
err := r.SDK.ReadData()
if err != nil {
return err
}
r.viewData.TotalBytes = r.TotalBytes
// Send the data to the view
select {
case r.viewCh <- &r.viewData:
// Sent the data
default:
// Dropped the frame!
}
// Write the data to the file
select {
case r.recorderCh <- r.SDK.Buffer:
// Sent the data
default:
// Dropped the frame!
}
}
if err := enc.Encode(beam.Data); err != nil {
log.Fatal(err)
}
<-ticker.C
}
}
+137 -17
View File
@@ -3,50 +3,157 @@
package mockserver
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"unsafe"
bngsdk "github.com/ESilva15/gobngsdk"
)
// Replay replays a given file <fp> in a UDP server <addr>:<port>
func Replay(ctx context.Context, address string, port int, loop bool, fp string) error {
fileInfo, err := os.Stat(fp)
type ViewData struct {
SDK *bngsdk.BeamNGSDK
SizeRead int64
}
// Replayer does the replaying
// Should we make a "player" struct that can record and replay?
type Replayer struct {
SDK bngsdk.BeamNGSDK
DataSourcePath string
Socket *UDPTransport
// Streams
dataViewCh chan ViewData
socketCh chan []byte
// Mut
mut sync.RWMutex
// View
viewData ViewData
}
func NewReplayer(address string, port int, fp string) (*Replayer, error) {
udp, err := NewUDPTransport(address, port)
if err != nil {
return fmt.Errorf("error stating file: %v", err)
return nil, err
}
bin, err := os.Open(fp)
replayer := &Replayer{
DataSourcePath: fp,
SDK: bngsdk.BeamNGSDK{
Data: &bngsdk.Outgauge{},
Buffer: make([]byte, unsafe.Sizeof(bngsdk.Outgauge{})),
},
Socket: udp,
viewData: ViewData{},
dataViewCh: make(chan ViewData, 1),
socketCh: make(chan []byte, 1),
}
return replayer, nil
}
// renderToTerminal will render the data for the users viewing pleasure
func (r *Replayer) renderToTerminal(ctx context.Context) {
fileInfo, err := os.Stat(r.DataSourcePath)
if err != nil {
// NOTE: learn how to handle this error
// return fmt.Errorf("error stating file: %v", err)
}
// NOTE: temporary until I make a better view
var s strings.Builder
var bytesReader bytes.Reader
for {
select {
case <-ctx.Done():
return
case data := <-r.dataViewCh:
// Reset to the start of the terminal
s.Reset()
fmt.Fprintf(os.Stdout, "\x1b[2J\x1b[H")
bytesReader.Reset(data.SDK.Buffer)
err := binary.Read(&bytesReader, binary.LittleEndian, r.SDK.Data)
if err != nil {
fmt.Fprintf(&s, "FAILED TO PARSE DATA\nError: %+v", err)
fmt.Fprint(os.Stdout, s.String())
continue
}
percent := int(float64(data.SizeRead) / float64(fileInfo.Size()) * 100)
fmt.Fprintf(&s, "Replayed: %d%%\n", percent)
stringifyOutgaugeData(&s, data.SDK)
fmt.Fprint(os.Stdout, s.String())
}
}
}
// writeToUDPSocket will write the telemetry data to the UDP socket
func (r *Replayer) writeToUDPSocket(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case data := <-r.socketCh:
r.mut.RLock()
_, err := r.Socket.Send(data)
r.mut.RUnlock()
if err != nil {
panic(fmt.Sprintf("error writing buffer to socket: %+v", err))
continue
// NOTE: log the error somewhere maybe
// return err
}
}
}
}
// Replay replays a given file <fp> in a UDP server <addr>:<port>
func (r *Replayer) Replay(ctx context.Context, loop bool) error {
bin, err := os.Open(r.DataSourcePath)
if err != nil {
return fmt.Errorf("error opening file: %v", err)
}
reader := NewGobReader(bin)
udp, err := NewUDPTransport(address, port)
if err != nil {
return err
}
go r.renderToTerminal(ctx)
go r.writeToUDPSocket(ctx)
ticker := time.NewTicker(time.Second / 60)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
data, err := reader.Next()
r.mut.Lock()
err := reader.Next(r.SDK.Buffer)
r.mut.Unlock()
if err == io.EOF {
if !loop {
return udp.Close()
return r.Socket.Close()
}
err = reader.Reset()
if err != nil {
return err
}
continue
}
@@ -54,13 +161,26 @@ func Replay(ctx context.Context, address string, port int, loop bool, fp string)
return err
}
_, err = udp.Send(data)
if err != nil {
return err
// NOTE: Really like this???
r.viewData.SDK = &r.SDK
r.viewData.SizeRead = reader.TotalRead
// Send the data to the view
select {
case r.dataViewCh <- r.viewData:
// Sent the data
default:
// Dropped the frame!
}
// Send the data to the UDP socket
select {
case r.socketCh <- r.SDK.Buffer:
// Sent the data
default:
// Dropped the frame!
}
percent := int(float64(reader.TotalRead) / float64(fileInfo.Size()) * 100)
fmt.Printf("\rReplayed: %d%%", percent)
}
}
}
+64
View File
@@ -0,0 +1,64 @@
package mockserver
import (
"context"
"net"
"os"
"testing"
)
func BenchmarkReplayAsync(b *testing.B) {
// Dummy socket
addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
if err != nil {
b.Fatalf("failed to resolve UDP address: %v", err)
}
listener, err := net.ListenUDP("udp", addr)
if err != nil {
b.Fatalf("failed to start background UDP listener: %v", err)
}
defer listener.Close()
// Drain the socket
go func() {
buf := make([]byte, 65535)
for {
_, _, err := listener.ReadFrom(buf)
if err != nil {
return
}
}
}()
// Extract the random port assigned by the OS
assignedAddr := listener.LocalAddr().(*net.UDPAddr)
// Get the file path
filePath := "sunburstManual.bin"
if _, err := os.Stat(filePath); os.IsNotExist(err) {
filePath = "../" + filePath
}
// Reset the timer
b.ResetTimer()
// Benchmark loop
for i := 0; i < b.N; i++ {
ctx, cancel := context.WithCancel(context.Background())
replayer, err := NewReplayer(assignedAddr.IP.String(), assignedAddr.Port, filePath)
if err != nil {
cancel()
b.Fatalf("Error setting up replayer: %+v", err)
}
err = replayer.Replay(ctx, false)
if err != nil {
cancel()
b.Fatalf("Replay failed during benchmark run: %+v", err)
}
cancel()
}
}
+89
View File
@@ -0,0 +1,89 @@
package mockserver
import (
"fmt"
"strings"
bngsdk "github.com/ESilva15/gobngsdk"
)
const (
_ = iota
KiB = 1 << (10 * iota)
MiB
GiB
)
func stringifyRecordingProgress(s *strings.Builder, nBytes int) {
if nBytes < KiB {
fmt.Fprintf(s, "%d B", nBytes)
} else if nBytes < MiB {
fmt.Fprintf(s, "%.2f KiB", float64(nBytes)/float64(KiB))
} else if nBytes < GiB {
fmt.Fprintf(s, "%.2f MiB", float64(nBytes)/float64(MiB))
} else {
fmt.Fprintf(s, "%.2f GiB", float64(nBytes)/float64(GiB))
}
}
func stringifyOutgaugeData(s *strings.Builder, sdk *bngsdk.BeamNGSDK) {
// NOTE: write a string serialization function on the SDK itself
fmt.Fprint(s, "Outgauge {\n")
fmt.Fprintf(s, " Time: %d ms\n", sdk.Data.Time)
fmt.Fprintf(s, " Car: %s\n", sdk.Data.Car)
fmt.Fprintf(s, " Flags: %b\n", sdk.Data.Flags)
fmt.Fprintf(s, " Gear: %d\n", sdk.Data.Gear)
fmt.Fprintf(s, " Plid: %d\n", sdk.Data.Plid)
fmt.Fprintf(s, " Speed: %f m/s\n", sdk.Data.Speed)
fmt.Fprintf(s, " RPM: %f RPM\n", sdk.Data.RPM)
fmt.Fprintf(s, " Turbo: %f Bar\n", sdk.Data.Turbo)
fmt.Fprintf(s, " EngTemp: %f °C\n", sdk.Data.EngTemp)
fmt.Fprintf(s, " Fuel: %f\n", sdk.Data.Fuel)
fmt.Fprintf(s, " OilPressure: %f Bar\n", sdk.Data.OilPressure)
fmt.Fprintf(s, " OilTemp: %f °C\n", sdk.Data.OilTemp)
fmt.Fprintf(s, " DashLights: %b\n", sdk.Data.DashLights)
fmt.Fprintf(s, " ShowLights: %b\n", sdk.Data.ShowLights)
fmt.Fprintf(s, " Throttle: %f\n", sdk.Data.Throttle)
fmt.Fprintf(s, " Brakes: %f\n", sdk.Data.Brake)
fmt.Fprintf(s, " Clutch: %f\n", sdk.Data.Clutch)
fmt.Fprintf(s, " Display1: %s\n", sdk.Data.Display1)
fmt.Fprintf(s, " Display2: %s\n", sdk.Data.Display2)
fmt.Fprintf(s, " ID: %d\n", sdk.Data.ID)
fmt.Fprint(s, "}\n\n")
fmt.Fprint(s, "DashLights {\n")
fmt.Fprintf(s, " DL_SHIFT: %t\n", sdk.HasShiftLight())
fmt.Fprintf(s, " DL_FULLBEAM: %t\n", sdk.HasHighBeamLight())
fmt.Fprintf(s, " DL_HANDBRAKE: %t\n", sdk.HasHandbrakeLight())
fmt.Fprintf(s, " DL_PITSPEED: %t\n", sdk.HasPitspeed())
fmt.Fprintf(s, " DL_TC: %t\n", sdk.HasTractionControlLight())
fmt.Fprintf(s, " DL_SIGNAL_L: %t\n", sdk.HasLeftIndicatorLight())
fmt.Fprintf(s, " DL_SIGNAL_R: %t\n", sdk.HasRightIndicatorLight())
fmt.Fprintf(s, " DL_SIGNAL_ANY: %t\n", sdk.HasAnyIndicatorLight())
fmt.Fprintf(s, " DL_OILWARN: %t\n", sdk.HasOilLight())
fmt.Fprintf(s, " DL_BATTERY: %t\n", sdk.HasBatteryLight())
fmt.Fprintf(s, " DL_ABS: %t\n", sdk.HasABSLight())
fmt.Fprintf(s, " DL_SPARE: %t\n", sdk.Data.DashLights&bngsdk.DL_SPARE != 0)
fmt.Fprint(s, "}\n\n")
fmt.Fprint(s, "ShowLights {\n") // Fixed typo "ShowLigths"
fmt.Fprintf(s, " DL_SHIFT: %t\n", sdk.ShiftLight())
fmt.Fprintf(s, " DL_FULLBEAM: %t\n", sdk.HighBeam())
fmt.Fprintf(s, " DL_HANDBRAKE: %t\n", sdk.Handbrake())
fmt.Fprintf(s, " DL_PITSPEED: %t\n", sdk.Pitspeed())
fmt.Fprintf(s, " DL_TC: %t\n", sdk.TractionControl())
fmt.Fprintf(s, " DL_SIGNAL_L: %t\n", sdk.LeftIndicator())
fmt.Fprintf(s, " DL_SIGNAL_R: %t\n", sdk.RightIndicator())
fmt.Fprintf(s, " DL_SIGNAL_ANY: %t\n", sdk.AnyIndicator())
fmt.Fprintf(s, " DL_OILWARN: %t\n", sdk.OilLight())
fmt.Fprintf(s, " DL_BATTERY: %t\n", sdk.BatteryLight())
fmt.Fprintf(s, " DL_ABS: %t\n", sdk.ABS())
fmt.Fprintf(s, " DL_SPARE: %t\n", sdk.Data.ShowLights&bngsdk.DL_SPARE != 0)
fmt.Fprint(s, "}\n\n")
fmt.Fprint(s, "Flags {\n")
fmt.Fprintf(s, " OG_TURBO (Has Turbo): %t\n", sdk.HasTurbo())
fmt.Fprintf(s, " OG_KM (Is Metric): %t\n", sdk.PrefersKm())
fmt.Fprintf(s, " OG_BAR (Pressure): %t\n", sdk.PrefersBAR())
fmt.Fprint(s, "}")
}