Compare commits

...
28 Commits
Author SHA1 Message Date
esilva 3b46b85eec Merge pull request 'chore: updated the README' (#6) from docs into master
Reviewed-on: #6

Closes #1
2026-11-08 23:24:41 +00:00
esilva c6129d0351 chore: updated the README 2026-11-08 23:24:08 +00:00
esilva cd7850987c bump the SDK versions 2026-09-17 00:19:38 +01:00
esilva 571b192f65 got the beamng version wrong 2026-09-17 00:18:27 +01:00
esilva 2171008c84 Merge pull request 'Update beamng to 2.0.0' (#3) from update-beamng-to-2.0.0 into master
Reviewed-on: #3
2026-09-17 00:10:10 +01:00
esilva 900d0cfbe9 updated the recorder gobngsdk v2 2026-09-17 00:09:40 +01:00
esilva 202dd75a65 updated the beamng replayer 2026-09-16 23:48:18 +01:00
esilva d5b26abb6e This was required for the previous commit 2026-09-14 18:02:02 +01:00
esilva c75936c19d Got iRacing working on ESDI, I will version this correctly when time comes 2026-09-14 18:01:50 +01:00
esilva e65c723d25 Merge pull request 'Added support for replaying iracing .ibt recordings' (#2) from iracing-mockserver into master
Reviewed-on: #2
2026-08-24 16:16:41 +01:00
esilva 9f54f8f6f7 Added support for replaying iracing .ibt recordings 2026-08-24 16:15:58 +01:00
esilva 25c81ada32 fix the description for the beamng command 2026-07-09 11:58:30 +01:00
esilva 9b19731858 starting the foundation for multiple types of telemetry data 2026-07-08 23:19:08 +01:00
esilva 0d0567c070 rename project 2026-07-08 22:54:56 +01:00
esilva f569f46499 Bump the BeamNG SDK and report the title for the window 2026-07-06 23:42:08 +01:00
esilva c185289c74 Slight memory usage reduction 2026-07-01 10:12:07 +01:00
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
21 changed files with 759 additions and 291 deletions
+3
View File
@@ -1 +1,4 @@
*.bin *.bin
*.work*
*.pprof
*.log
+60 -8
View File
@@ -1,18 +1,70 @@
# BeamNGMockOG # TelemetryMockserver
Utility to both record (with the caveat that it doesn't record yet) and replay Utility to both record and replay telemetry data from multiple simulators.
binary data relating to the Outgauge struct of beamng.
This will help me develop some stuff I'm doing for `ESDI` and my peripherals This will help me develop some stuff I'm doing for `ESDI` and my peripherals
without having to be playing the game while doing it (fans are noisy). without having to be playing the game while doing it (fans are noisy).
## Related projects
- [ESDI](https://github.com/ESilva15/ESDI)
- [iRacing Go SDK](https://github.com/ESilva15/goirsdk)
- [BeamNG Go SDK](https://github.com/ESilva15/gobngsdk)
# Installation # Installation
`go install github.com/ESilva15/BeamNGMockOg@latest` `go install github.com/ESilva15/TelemetryMockserver@latest`
# Usage # Usage
To start replaying: To start replaying (BeamNG as an example):
`BeamNGMockOg replay -a 127.0.0.1 -p 4443 -i sunburstManual.bin` `telemetrymockserver beamng 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` To start recording (BeamNG as an example):
`TelemetryMockserver beamng 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`
### TODO:
- [ ] Create the auto completion file and add it to `$FPATH`
- [ ] Create a shortcut so we don't have to type out `telemetrymockserver` everytime
### 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:
Note: this were made before introducing the real time visualizer
```
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
```
#### Current results
```
goos: linux
goarch: amd64
pkg: github.com/ESilva15/BeamNGMockOg/mockserver
cpu: AMD Ryzen 7 5800X3D 8-Core Processor
BenchmarkReplayAsync-16 1 109433890158 ns/op 1673128 B/op 112986 allocs/op
PASS
ok github.com/ESilva15/BeamNGMockOg/mockserver 109.439s
```
+94
View File
@@ -0,0 +1,94 @@
package cmd
import (
"context"
"fmt"
"log/slog"
beamng "github.com/ESilva15/TelemetryMockserver/internal/mockservers/beamng"
"github.com/spf13/cobra"
)
// beamNGCmd is the parent command for the BeamNG agent actions
var beamNGCmd = &cobra.Command{
Use: "beamng",
Short: "BeamNG telemetry utilities",
Args: nil,
}
var beamNGRecordCMD = &cobra.Command{
Use: "record",
Short: "record -o <path-to-output-file>",
Long: `record will store the data from the given UDP server to the
filepath given by -o`,
Args: nil,
Run: recordAction,
}
var beamNGReplayCMD = &cobra.Command{
Use: "replay",
Short: "replay -i <path-to-input-file>",
Long: "replay will replay the data on the given filepath on a UDP server",
Args: nil,
Run: replayAction,
}
func recordAction(cmd *cobra.Command, args []string) {
outputFile, _ := cmd.Flags().GetString("output")
address, _ := cmd.Flags().GetString("address")
port, _ := cmd.Flags().GetInt("port")
recorder, err := beamng.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)
}
}
func replayAction(cmd *cobra.Command, args []string) {
inputFile, _ := cmd.Flags().GetString("input")
address, _ := cmd.Flags().GetString("address")
port, _ := cmd.Flags().GetInt("port")
loop, _ := cmd.Flags().GetBool("loop")
replayer, err := beamng.NewReplayer(address, port, inputFile)
if err != nil {
slog.Error("Something went wrong setting up the player", "err", err)
return
}
// NOTE: is this doing anything at all??
ctx := context.Background()
err = replayer.Replay(ctx, loop)
if err != nil {
slog.Error("Something went wrong while playing the file", "err", err)
return
}
}
func init() {
// Beamng commnad flags
beamNGCmd.PersistentFlags().StringP("address", "a", "127.0.0.1", "Address for the UDP server")
beamNGCmd.MarkFlagRequired("address")
beamNGCmd.PersistentFlags().IntP("port", "p", 4444, "Port for the UDP server")
beamNGCmd.MarkFlagRequired("port")
// Record command flags
beamNGRecordCMD.Flags().StringP("output", "o", "output.bin", "output file for recording")
beamNGRecordCMD.MarkFlagRequired("output")
// Replay command flags
beamNGReplayCMD.Flags().BoolP("loop", "l", false, "whether to loop the recording")
beamNGReplayCMD.Flags().StringP("input", "i", "input.bin", "input file for reading")
beamNGReplayCMD.MarkFlagRequired("input")
rootCmd.AddCommand(beamNGCmd)
beamNGCmd.AddCommand(beamNGRecordCMD, beamNGReplayCMD)
}
+2 -2
View File
@@ -9,8 +9,8 @@ import (
// rootCmd represents the base command when called without any subcommands // rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "bngmock", Use: "telemetrymockserver",
Short: "CLI for a BeamNG OG mockserver", Short: "CLI for mocking and recording data from different sources. Primarily for simracing",
Long: ``, Long: ``,
} }
+54
View File
@@ -0,0 +1,54 @@
package cmd
import (
"context"
"fmt"
"github.com/ESilva15/TelemetryMockserver/internal/mockservers/iracing"
"github.com/spf13/cobra"
)
// beamNGCmd is the parent command for the BeamNG agent actions
var iracingCmd = &cobra.Command{
Use: "iracing",
Short: "iRacing telemetry utility",
Args: nil,
}
var iracingReplayCMD = &cobra.Command{
Use: "replay",
Short: "replay -i <input-file> -o <output-memory-map-file>",
Long: "replays the <input-file> in the <output-memory-map-file>",
Args: nil,
Run: iracingReplayAction,
}
func iracingReplayAction(cmd *cobra.Command, args []string) {
// We need to get the path of the ibt.file
// outputFile, _ := cmd.Flags().GetString("output")
// inputFile, _ := cmd.Flags().GetString("input")
replayer, err := iracing.NewReplayer("", "")
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 := replayer.Replay(ctx, false); err != nil {
fmt.Printf("Something went wrong while playing the file: %v", err)
}
}
func init() {
rootCmd.AddCommand(iracingCmd)
iracingCmd.AddCommand(iracingReplayCMD)
// iracingReplayCMD flags
iracingReplayCMD.Flags().StringP("input", "i", "input.ibt", "input file")
// iracingReplayCMD.MarkFlagRequired("input")
iracingReplayCMD.Flags().StringP("output", "o", "memmap.file", "output memory mapped file")
// iracingReplayCMD.MarkFlagRequired("output")
}
-35
View File
@@ -1,35 +0,0 @@
package cmd
import (
"fmt"
"github.com/ESilva15/BeamNGMockOg/mockserver"
"github.com/spf13/cobra"
)
func recordAction(cmd *cobra.Command, args []string) {
outputFile, _ := cmd.Flags().GetString("output")
address, _ := cmd.Flags().GetString("address")
port, _ := cmd.Flags().GetInt("port")
if err := mockserver.Record(address, port, outputFile); err != nil {
fmt.Printf("Something went wrong while recording the file: %v", err)
}
}
// shelf
var recordCmd = &cobra.Command{
Use: "record",
Short: "record -o <path-to-bin-file>",
Long: `record will store the data from the given UDP server to the
filepath given by -i`,
Args: nil,
Run: recordAction,
}
func init() {
rootCmd.AddCommand(recordCmd)
recordCmd.PersistentFlags().StringP("output", "o", "output.bin", "output file for recording")
}
-38
View File
@@ -1,38 +0,0 @@
package cmd
import (
"context"
"fmt"
"github.com/ESilva15/BeamNGMockOg/mockserver"
"github.com/spf13/cobra"
)
func replayAction(cmd *cobra.Command, args []string) {
inputFile, _ := cmd.Flags().GetString("input")
address, _ := cmd.Flags().GetString("address")
port, _ := cmd.Flags().GetInt("port")
loop, _ := cmd.Flags().GetBool("loop")
ctx := context.Background()
if err := mockserver.Replay(ctx, address, port, loop, inputFile); err != nil {
fmt.Printf("Something went wrong while playing the file: %v", err)
}
}
// shelf
var replayCmd = &cobra.Command{
Use: "replay",
Short: "replay -i <path-to-bin-file>",
Long: `replay will replay the data on the given filepath on a UDP server`,
Args: nil,
Run: replayAction,
}
func init() {
rootCmd.AddCommand(replayCmd)
replayCmd.PersistentFlags().StringP("input", "i", "nofile.bin", "input file for serving")
replayCmd.PersistentFlags().BoolP("loop", "l", false, "loop replay after finishing")
}
+3
View File
@@ -0,0 +1,3 @@
package constants
const ProgramName = "TelemetryMockserver"
+9 -4
View File
@@ -1,15 +1,20 @@
module github.com/ESilva15/BeamNGMockOg module github.com/ESilva15/TelemetryMockserver
replace github.com/ESilva15/gobngsdk => ../pkg/bngsdk
go 1.23.2 go 1.23.2
require ( require (
github.com/ESilva15/gobngsdk v0.0.0-00010101000000-000000000000 github.com/ESilva15/gobngsdk v1.2.0
github.com/ESilva15/goirsdk v0.3.8
github.com/spf13/cobra v1.10.1 github.com/spf13/cobra v1.10.1
) )
require ( require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.9 // indirect github.com/spf13/pflag v1.0.9 // indirect
golang.org/x/sys v0.29.0 // indirect
golang.org/x/text v0.19.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
) )
//
// replace github.com/ESilva15/goirsdk => ../pkg/goirsdk/
// replace github.com/ESilva15/gobngsdk => ../pkg/gobngsdk/
+12 -2
View File
@@ -1,6 +1,10 @@
github.com/ESilva15/gobngsdk v0.0.2 h1:N6stNOE14Wg80BAZMFu/Qd9Qa/J0DmExCfdPoDf7lco= github.com/ESilva15/gobngsdk v1.2.0 h1:jX2ByFaIHnjCdPmrj1JiqCoNRLyu4vqIXC7++EUOCK4=
github.com/ESilva15/gobngsdk v0.0.2/go.mod h1:cKLaZRgM0tGGXDvosaSjHnxeyC5Y6rg7zCLqEUJnOzw= github.com/ESilva15/gobngsdk v1.2.0/go.mod h1:cKLaZRgM0tGGXDvosaSjHnxeyC5Y6rg7zCLqEUJnOzw=
github.com/ESilva15/goirsdk v0.3.8 h1:Eiabg4TqMkJQCImLEqwN93/BAuafbYyTrNXxg/Ck9bQ=
github.com/ESilva15/goirsdk v0.3.8/go.mod h1:5borQbw+L4fe9b58JFHRHZwrzz0sMVAteuYbRnFOc0Q=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
@@ -8,5 +12,11 @@ github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s=
github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0= github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+114
View File
@@ -0,0 +1,114 @@
package mockserver
import (
"bytes"
"context"
"fmt"
"log/slog"
"os"
"sync"
"time"
"github.com/ESilva15/TelemetryMockserver/constants"
bngsdk "github.com/ESilva15/gobngsdk"
)
type recorderViewData struct {
TotalBytes int64
Og bngsdk.Outgauge
}
type Recorder struct {
SDK *bngsdk.BeamNGSDK
// Views
mut sync.RWMutex
viewDataMut sync.RWMutex
viewData recorderViewData
viewCh chan *recorderViewData
}
func NewRecorder(fp string, address string, port int) (*Recorder, error) {
var recorder Recorder
var err error
recorder.SDK, err = bngsdk.NewBngSDK(bngsdk.Options{
Logger: slog.Default().With("SDK", "BeamNG"),
SourceType: bngsdk.UDPData,
ImportUDPAddress: address,
ImportUDPPort: port,
ExportData: true,
ExportDataType: bngsdk.BinaryFile,
ExportDataPath: fp,
})
if err != nil {
return nil, err
}
recorder.viewData = recorderViewData{}
recorder.viewCh = make(chan *recorderViewData, 1)
return &recorder, nil
}
func (r *Recorder) Close() {
r.SDK.Close()
}
func (r *Recorder) view(ctx context.Context) {
var buf bytes.Buffer
buf.Grow(2048)
for {
select {
case <-ctx.Done():
return
case viewData := <-r.viewCh:
buf.Reset()
buf.WriteString("\x1b[2J\x1b[H")
fmt.Fprintf(&buf, "\x1b]0;%s - Recording ", constants.ProgramName)
stringifyRecordingProgress(&buf, viewData.TotalBytes)
fmt.Fprintf(&buf, "\x07")
stringifyRecordingProgress(&buf, viewData.TotalBytes)
fmt.Fprintf(&buf, "\n\n")
r.viewDataMut.RLock()
stringifyOutgaugeData(&buf, &viewData.Og)
r.viewDataMut.RUnlock()
_, _ = buf.WriteTo(os.Stdout)
}
}
}
// Record records data from the UDP connection created by address and port
func (r *Recorder) Record(ctx context.Context) error {
ticker := time.NewTicker(time.Second / 60)
defer ticker.Stop()
go r.view(ctx)
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
og, err := r.SDK.Update()
if err != nil {
return err
}
r.viewData.TotalBytes = r.SDK.GetTotalWritten()
r.viewData.Og = *og
// Send the data to the view
select {
case r.viewCh <- &r.viewData:
// Sent the data
default:
// Dropped the frame!
}
}
}
}
+124
View File
@@ -0,0 +1,124 @@
// Package mockserver is the core of this program and it will have the API
// to record binary data from the UDP server and then be able to mock it
package mockserver
import (
"bytes"
"context"
"fmt"
"log/slog"
"math"
"os"
"sync"
"time"
"github.com/ESilva15/TelemetryMockserver/constants"
bngsdk "github.com/ESilva15/gobngsdk"
)
type ViewData struct {
Outgauge bngsdk.Outgauge
SizeRead int64
FileSize int64
}
// Replayer does the replaying
// Should we make a "player" struct that can record and replay?
type Replayer struct {
SDK *bngsdk.BeamNGSDK
// Streams
dataViewCh chan ViewData
// Mut
mut sync.RWMutex
// View
viewData ViewData
}
func NewReplayer(address string, port int, fp string) (*Replayer, error) {
sdk, err := bngsdk.NewBngSDK(bngsdk.Options{
Logger: slog.Default().With("SDK", "BeamNG"),
SourceType: bngsdk.BinaryFile,
BinSourcePath: fp,
ExportData: true,
ExportDataType: bngsdk.UDPData,
ExportUDPAddress: address,
ExportUDPPort: port,
Loop: true,
})
if err != nil {
return nil, err
}
replayer := &Replayer{
SDK: sdk,
dataViewCh: make(chan ViewData, 1),
}
return replayer, nil
}
// renderToTerminal will render the data for the users viewing pleasure
func (r *Replayer) renderToTerminal(ctx context.Context) {
var buf bytes.Buffer
buf.Grow(2048)
for {
select {
case <-ctx.Done():
return
case data := <-r.dataViewCh:
// Reset to the start of the terminal
// percent := int(float64(data.SizeRead) / float64(data.FileSize) * 100)
percent := int(math.Round((float64(data.SizeRead) / float64(data.FileSize)) * 100))
buf.Reset()
buf.WriteString("\x1b[2J\x1b[H")
fmt.Fprintf(&buf, "\x1b]0;%s - Replaying %d%%\x07", constants.ProgramName, percent)
fmt.Fprintf(&buf, "Replayed: %d%%\n", percent)
stringifyOutgaugeData(&buf, &data.Outgauge)
buf.WriteTo(os.Stdout)
}
}
}
// Replay replays a given file <fp> in a UDP server <addr>:<port>
func (r *Replayer) Replay(ctx context.Context, loop bool) error {
go r.renderToTerminal(ctx)
ticker := time.NewTicker(time.Second / 60)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
og, err := r.SDK.Update()
if err != nil {
// TODO: log here
slog.Error("an error occurred when updating", "err", err)
return err
}
r.mut.Lock()
r.viewData.SizeRead = r.SDK.GetTotalRead()
r.viewData.FileSize = r.SDK.GetSourceSize()
r.viewData.Outgauge = *og
r.mut.Unlock()
// Send the data to the view
select {
case r.dataViewCh <- r.viewData:
// Sent the data
default:
// Dropped the frame!
}
}
}
}
@@ -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 (
"bytes"
"fmt"
bngsdk "github.com/ESilva15/gobngsdk"
)
const (
_ = iota
KiB = 1 << (10 * iota)
MiB
GiB
)
func stringifyRecordingProgress(s *bytes.Buffer, nBytes int64) {
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 *bytes.Buffer, og *bngsdk.Outgauge) {
// NOTE: write a string serialization function on the SDK itself
fmt.Fprint(s, "Outgauge {\n")
fmt.Fprintf(s, " Time: %d ms\n", og.Time)
fmt.Fprintf(s, " Car: %s\n", og.Car)
fmt.Fprintf(s, " Flags: %b\n", og.Flags)
fmt.Fprintf(s, " Gear: %d\n", og.Gear)
fmt.Fprintf(s, " Plid: %d\n", og.Plid)
fmt.Fprintf(s, " Speed: %f m/s\n", og.Speed)
fmt.Fprintf(s, " RPM: %f RPM\n", og.RPM)
fmt.Fprintf(s, " Turbo: %f Bar\n", og.Turbo)
fmt.Fprintf(s, " EngTemp: %f °C\n", og.EngTemp)
fmt.Fprintf(s, " Fuel: %f\n", og.Fuel)
fmt.Fprintf(s, " OilPressure: %f Bar\n", og.OilPressure)
fmt.Fprintf(s, " OilTemp: %f °C\n", og.OilTemp)
fmt.Fprintf(s, " DashLights: %b\n", og.DashLights)
fmt.Fprintf(s, " ShowLights: %b\n", og.ShowLights)
fmt.Fprintf(s, " Throttle: %f\n", og.Throttle)
fmt.Fprintf(s, " Brakes: %f\n", og.Brake)
fmt.Fprintf(s, " Clutch: %f\n", og.Clutch)
fmt.Fprintf(s, " Display1: %s\n", og.Display1)
fmt.Fprintf(s, " Display2: %s\n", og.Display2)
fmt.Fprintf(s, " ID: %d\n", og.ID)
fmt.Fprint(s, "}\n\n")
fmt.Fprint(s, "DashLights {\n")
fmt.Fprintf(s, " DL_SHIFT: %t\n", og.HasShiftLight())
fmt.Fprintf(s, " DL_FULLBEAM: %t\n", og.HasHighBeamLight())
fmt.Fprintf(s, " DL_HANDBRAKE: %t\n", og.HasHandbrakeLight())
fmt.Fprintf(s, " DL_PITSPEED: %t\n", og.HasPitspeed())
fmt.Fprintf(s, " DL_TC: %t\n", og.HasTractionControlLight())
fmt.Fprintf(s, " DL_SIGNAL_L: %t\n", og.HasLeftIndicatorLight())
fmt.Fprintf(s, " DL_SIGNAL_R: %t\n", og.HasRightIndicatorLight())
fmt.Fprintf(s, " DL_SIGNAL_ANY: %t\n", og.HasAnyIndicatorLight())
fmt.Fprintf(s, " DL_OILWARN: %t\n", og.HasOilLight())
fmt.Fprintf(s, " DL_BATTERY: %t\n", og.HasBatteryLight())
fmt.Fprintf(s, " DL_ABS: %t\n", og.HasABSLight())
fmt.Fprintf(s, " DL_SPARE: %t\n", og.HasSpare())
fmt.Fprint(s, "}\n\n")
fmt.Fprint(s, "ShowLights {\n") // Fixed typo "ShowLigths"
fmt.Fprintf(s, " DL_SHIFT: %t\n", og.ShiftLight())
fmt.Fprintf(s, " DL_FULLBEAM: %t\n", og.HighBeam())
fmt.Fprintf(s, " DL_HANDBRAKE: %t\n", og.Handbrake())
fmt.Fprintf(s, " DL_PITSPEED: %t\n", og.Pitspeed())
fmt.Fprintf(s, " DL_TC: %t\n", og.TractionControl())
fmt.Fprintf(s, " DL_SIGNAL_L: %t\n", og.LeftIndicator())
fmt.Fprintf(s, " DL_SIGNAL_R: %t\n", og.RightIndicator())
fmt.Fprintf(s, " DL_SIGNAL_ANY: %t\n", og.AnyIndicator())
fmt.Fprintf(s, " DL_OILWARN: %t\n", og.OilLight())
fmt.Fprintf(s, " DL_BATTERY: %t\n", og.BatteryLight())
fmt.Fprintf(s, " DL_ABS: %t\n", og.ABS())
fmt.Fprintf(s, " DL_SPARE: %t\n", og.Spare())
fmt.Fprint(s, "}\n\n")
fmt.Fprint(s, "Flags {\n")
fmt.Fprintf(s, " OG_TURBO (Has Turbo): %t\n", og.HasTurbo())
fmt.Fprintf(s, " OG_KM (Is Metric): %t\n", og.PrefersKm())
fmt.Fprintf(s, " OG_BAR (Pressure): %t\n", og.PrefersBAR())
fmt.Fprint(s, "}")
}
+94
View File
@@ -0,0 +1,94 @@
package iracing
import (
"context"
"fmt"
"log"
"log/slog"
"sync"
"time"
"github.com/ESilva15/goirsdk"
)
type Replayer struct {
SDK *goirsdk.IBT
// DataSourcePath string
// Socket *UDPTransport
// Output memory mapped file
outputMmap string
// Streams
// dataViewCh chan ViewData
// socketCh chan []byte
// Mut
mut sync.RWMutex
// View
// viewData ViewData
}
func NewReplayer(input string, output string) (*Replayer, error) {
ibt, err := goirsdk.Init(goirsdk.Options{
Logger: slog.Default(),
SourceType: goirsdk.IBTFile,
SourcePath: "../testTelemetry/gt3_mustang_bathurst.ibt",
IBTExportType: goirsdk.SharedMemoryFile,
IBTExport: true,
})
if err != nil {
return nil, err
}
replayer := &Replayer{
SDK: ibt,
}
return replayer, nil
}
func (r *Replayer) Replay(ctx context.Context, loop bool) error {
mainLoopTicker := time.NewTicker(time.Second / 240)
defer mainLoopTicker.Stop()
for {
// Update the data that the SDK is holding with the next tick
_, err := r.SDK.Update(100 * time.Millisecond)
if err != nil {
log.Printf("could not update data: %v", err)
continue
}
// Vehicle Movement data gathered from the names we can find on the
// telemetry_docs.pdf file
// - I wish to make this less verbose if possible
if _, ok := r.SDK.Vars.Vars["Gear"]; !ok {
log.Fatal("Field `Gear` doesn't exist")
}
if _, ok := r.SDK.Vars.Vars["RPM"]; !ok {
log.Fatal("Field `RPM` doesn't exist")
}
if _, ok := r.SDK.Vars.Vars["Speed"]; !ok {
log.Fatal("Field `Speed` doesn't exist")
}
gear := int32(r.SDK.Vars.Vars["Gear"].Value.(int))
rpm := int32(r.SDK.Vars.Vars["RPM"].Value.(float32))
speed := int32(r.SDK.Vars.Vars["Speed"].Value.(float32))
sessionState := r.SDK.Vars.Vars["SessionState"].Value.(int)
fmt.Printf("\033[?25l\033[2J\033[H")
fmt.Printf("Gear: %d, RPM: %d, Speed: %d\n", gear, rpm, speed)
fmt.Printf("\n")
fmt.Printf("IsConnected: %t\n", r.SDK.IsConnected())
fmt.Printf(" SessionStatusConnected: %t\n", r.SDK.SessionStatusConnected())
fmt.Printf(" SessionStatusInvalid: %t\n", r.SDK.SessionStateInvalid())
fmt.Printf(" SessionState: %d\n", sessionState)
<-mainLoopTicker.C
}
}
+10
View File
@@ -0,0 +1,10 @@
// Package mockservers defines the available mockserver for the telemetry data
package mockservers
import "context"
// Mockserver defines what a mockserver should do
type Mockserver interface {
Replay(context.Context, bool)
Record(output string)
}
+27 -1
View File
@@ -1,6 +1,32 @@
package main package main
import "github.com/ESilva15/BeamNGMockOg/cmd" import (
"log/slog"
"os"
"github.com/ESilva15/TelemetryMockserver/cmd"
)
func init() {
_ = setupLogger()
}
func setupLogger() error {
output, err := os.OpenFile("./output.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o755)
if err != nil {
return err
}
logger := slog.New(
slog.NewTextHandler(output, &slog.HandlerOptions{
Level: slog.LevelDebug,
}),
)
slog.SetDefault(logger)
return nil
}
func main() { func main() {
cmd.Execute() cmd.Execute()
-55
View File
@@ -1,55 +0,0 @@
package mockserver
import (
"bytes"
"encoding/binary"
"encoding/gob"
"io"
sdk "github.com/ESilva15/gobngsdk"
)
type GobReader struct {
TotalRead int
File io.ReadSeeker
Dec *gob.Decoder
}
func NewGobReader(r io.ReadSeeker) *GobReader {
return &GobReader{
TotalRead: 0,
File: r,
Dec: gob.NewDecoder(r),
}
}
func (g *GobReader) Reset() error {
_, err := g.File.Seek(0, io.SeekStart)
if err != nil {
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)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
err = binary.Write(buf, binary.LittleEndian, &og)
if err != nil {
return nil, err
}
g.TotalRead += len(buf.Bytes())
return buf.Bytes(), nil
}
-41
View File
@@ -1,41 +0,0 @@
package mockserver
import (
"encoding/gob"
"log"
"os"
"time"
bngsdk "github.com/ESilva15/gobngsdk"
)
// Record records data from the UDP connection created by address and port
func Record(address string, port int, filePath string) error {
ticker := time.NewTicker(time.Second / 60)
defer ticker.Stop()
// Create the output file
bin, err := os.Create(filePath)
if err != nil {
return err
}
// 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
}
if err := enc.Encode(beam.Data); err != nil {
log.Fatal(err)
}
<-ticker.C
}
}
-66
View File
@@ -1,66 +0,0 @@
// Package mockserver is the core of this program and it will have the API
// to record binary data from the UDP server and then be able to mock it
package mockserver
import (
"context"
"fmt"
"io"
"os"
"time"
)
// 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)
if err != nil {
return fmt.Errorf("error stating file: %v", err)
}
bin, err := os.Open(fp)
if err != nil {
return fmt.Errorf("error opening file: %v", err)
}
reader := NewGobReader(bin)
udp, err := NewUDPTransport(address, port)
if err != nil {
return err
}
ticker := time.NewTicker(time.Second / 60)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
data, err := reader.Next()
if err == io.EOF {
if !loop {
return udp.Close()
}
err = reader.Reset()
if err != nil {
return err
}
continue
}
if err != nil {
return err
}
_, err = udp.Send(data)
if err != nil {
return err
}
percent := int(float64(reader.TotalRead) / float64(fileInfo.Size()) * 100)
fmt.Printf("\rReplayed: %d%%", percent)
}
}
}
-39
View File
@@ -1,39 +0,0 @@
package mockserver
import (
"fmt"
"net"
)
type Transport interface {
Send(data []byte) error
Close() error
}
type UDPTransport struct {
Conn *net.UDPConn
Addr *net.UDPAddr
}
func NewUDPTransport(address string, port int) (*UDPTransport, error) {
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", address, port))
if err != nil {
return nil, err
}
conn, err := net.ListenUDP("udp", nil)
if err != nil {
return nil, err
}
return &UDPTransport{Conn: conn, Addr: addr}, nil
}
// Send will send a byte array of data trough the UDP server
func (u *UDPTransport) Send(data []byte) (int, error) {
return u.Conn.WriteToUDP(data, u.Addr)
}
func (u *UDPTransport) Close() error {
return u.Conn.Close()
}