The logger needs to be passed from the caller now - will change this in the future

This commit is contained in:
2026-09-10 15:13:42 +01:00
parent 7584b0ffcf
commit 052f4582c9
9 changed files with 93 additions and 72 deletions
+3 -3
View File
@@ -155,12 +155,12 @@ func (i *IBT) checkEngineWarningsBitfield(field int) bool {
log.Fatal("no EngineWarnings") log.Fatal("no EngineWarnings")
} }
bitfield, ok := val.Value.(int) bitfield, ok := val.Value.(uint32)
if !ok { if !ok {
log.Fatalf("unable to typecast EngineWarnings: %+v", val.Value) log.Fatalf("unable to typecast EngineWarnings: %+v", val)
} }
return bitfield&field != 0 return bitfield&uint32(field) != 0
} }
func (i *IBT) WaterTempWarning() bool { func (i *IBT) WaterTempWarning() bool {
+1 -7
View File
@@ -4,8 +4,6 @@ import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/ESilva15/goirsdk/logger"
) )
const ( const (
@@ -23,8 +21,6 @@ type DiskSubHeader struct {
// readSubheader will read the subheader contents out of the telemetry data // readSubheader will read the subheader contents out of the telemetry data
func (i *IBT) readSubheader() error { func (i *IBT) readSubheader() error {
log := logger.GetInstance()
var subheaderRaw [SubHeaderSize]byte var subheaderRaw [SubHeaderSize]byte
_, err := i.File.ReadAt(subheaderRaw[:], HeaderSize) _, err := i.File.ReadAt(subheaderRaw[:], HeaderSize)
if err != nil { if err != nil {
@@ -39,7 +35,7 @@ func (i *IBT) readSubheader() error {
if i.Opts.IBTExport { if i.Opts.IBTExport {
err = i.exportIBT(subheaderRaw[:], HeaderSize) err = i.exportIBT(subheaderRaw[:], HeaderSize)
if err != nil { if err != nil {
log.Printf("failed to export subheaders: %v\n", err) i.Opts.Logger.Debug("failed to export disksubheader", "err", err)
} }
} }
@@ -50,8 +46,6 @@ func (i *IBT) readSubheader() error {
// or nil if an error occurs. In which case the error return value is more // or nil if an error occurs. In which case the error return value is more
// valuable // valuable
func parseTelemetrySubHeader(buf [SubHeaderSize]byte) (*DiskSubHeader, error) { func parseTelemetrySubHeader(buf [SubHeaderSize]byte) (*DiskSubHeader, error) {
// utils.HexDump(buf[:])
dst := DiskSubHeader{} dst := DiskSubHeader{}
err := binary.Read(bytes.NewBuffer(buf[:]), binary.LittleEndian, &dst) err := binary.Read(bytes.NewBuffer(buf[:]), binary.LittleEndian, &dst)
if err != nil { if err != nil {
@@ -3,6 +3,8 @@ package main
import ( import (
"fmt" "fmt"
"log" "log"
"log/slog"
"os"
"time" "time"
"github.com/ESilva15/goirsdk" "github.com/ESilva15/goirsdk"
@@ -13,8 +15,20 @@ func msToKph(v float32) int {
} }
func main() { func main() {
output, err := os.OpenFile("./output.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o755)
if err != nil {
log.Fatalf("Failed to open log file: %+v", err)
}
logger := slog.New(
slog.NewTextHandler(output, &slog.HandlerOptions{
Level: slog.LevelDebug,
}),
)
// Instantiate our iRacing SDK instance // Instantiate our iRacing SDK instance
irsdk, err := goirsdk.Init(goirsdk.Options{ irsdk, err := goirsdk.Init(goirsdk.Options{
Logger: logger,
SourceType: goirsdk.IBTFile, SourceType: goirsdk.IBTFile,
SourcePath: "../../../../testTelemetry/mx5_2016Okayama_full_2024_10_19_22_02_12.ibt", SourcePath: "../../../../testTelemetry/mx5_2016Okayama_full_2024_10_19_22_02_12.ibt",
IBTExportType: goirsdk.SharedMemoryFile, IBTExportType: goirsdk.SharedMemoryFile,
@@ -3,6 +3,8 @@ package main
import ( import (
"fmt" "fmt"
"log" "log"
"log/slog"
"os"
"time" "time"
"github.com/ESilva15/goirsdk" "github.com/ESilva15/goirsdk"
@@ -13,8 +15,22 @@ func msToKph(v float32) int {
} }
func main() { func main() {
output, err := os.OpenFile("./output.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o755)
if err != nil {
log.Fatalf("Failed to open log file: %+v", err)
}
logger := slog.New(
slog.NewTextHandler(output, &slog.HandlerOptions{
Level: slog.LevelDebug,
}),
)
logger.Debug("Starting test")
// Instantiate our iRacing SDK instance // Instantiate our iRacing SDK instance
irsdk, err := goirsdk.Init(goirsdk.Options{ irsdk, err := goirsdk.Init(goirsdk.Options{
Logger: logger,
SourceType: goirsdk.SharedMemoryFile, SourceType: goirsdk.SharedMemoryFile,
}) })
if err != nil { if err != nil {
@@ -53,9 +69,29 @@ func main() {
gear := int32(irsdk.Vars.Vars["Gear"].Value.(int)) gear := int32(irsdk.Vars.Vars["Gear"].Value.(int))
rpm := int32(irsdk.Vars.Vars["RPM"].Value.(float32)) rpm := int32(irsdk.Vars.Vars["RPM"].Value.(float32))
speed := int32(msToKph(irsdk.Vars.Vars["Speed"].Value.(float32))) speed := int32(msToKph(irsdk.Vars.Vars["Speed"].Value.(float32)))
sessionState := irsdk.Vars.Vars["SessionState"].Value.(int)
trkloc := irsdk.Vars.Vars["PlayerTrackSurface"].Value.(int)
trksurf := irsdk.Vars.Vars["PlayerTrackSurfaceMaterial"].Value.(int)
pitsvflags := irsdk.Vars.Vars["PitSvFlags"].Value.(uint32)
fmt.Printf("\033[?25l\033[2J\033[H") fmt.Printf("\033[?25l\033[2J\033[H")
fmt.Printf("Gear: %d, RPM: %d, Speed: %d", gear, rpm, speed) fmt.Printf("Gear: %d, RPM: %d, Speed: %d\n", gear, rpm, speed)
fmt.Printf("SessionState: %s\n", goirsdk.SessionStateToString(sessionState))
fmt.Printf("TrkLoc: %s\n", goirsdk.TrkLocToString(trkloc))
fmt.Printf("TrkSurf: %s\n", goirsdk.TrkSurfToString(trksurf))
fmt.Printf("PitSvFlags: %d\n", pitsvflags)
fmt.Printf(" FL FR\n")
fmt.Printf(" %t %t\n", irsdk.LFTireChange(), irsdk.RFTireChange())
fmt.Printf("\n")
fmt.Printf(" RL RR\n")
fmt.Printf(" %t %t\n", irsdk.LRTireChange(), irsdk.RRTireChange())
fmt.Printf(" FuelFill: %t\n", irsdk.FuelFill())
fmt.Printf(" WindshieldTearoff: %t\n", irsdk.WindshieldTearoff())
fmt.Printf(" FastRepair: %t\n", irsdk.FastRepair())
fmt.Printf(" ClearTires: %t\n", irsdk.ClearTires())
fmt.Printf(" ClearWS: %t\n", irsdk.ClearWS())
fmt.Printf(" ClearFR: %t\n", irsdk.ClearFR())
fmt.Printf(" ClearFuel: %t\n", irsdk.ClearFuel())
<-mainLoopTicker.C <-mainLoopTicker.C
} }
+1 -5
View File
@@ -4,8 +4,6 @@ import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/ESilva15/goirsdk/logger"
) )
const ( const (
@@ -32,8 +30,6 @@ type TelemetryHeaders struct {
// readHeader will read the header out of the telemetry data // readHeader will read the header out of the telemetry data
func (i *IBT) readHeader() error { func (i *IBT) readHeader() error {
log := logger.GetInstance()
var headerRaw [FileHeaderSize]byte var headerRaw [FileHeaderSize]byte
_, err := i.File.ReadAt(headerRaw[:], 0) _, err := i.File.ReadAt(headerRaw[:], 0)
if err != nil { if err != nil {
@@ -48,7 +44,7 @@ func (i *IBT) readHeader() error {
if i.Opts.IBTExport { if i.Opts.IBTExport {
err = i.exportIBT(headerRaw[:], 0) err = i.exportIBT(headerRaw[:], 0)
if err != nil { if err != nil {
log.Printf("Failed to export headers: %v\n", err) i.Opts.Logger.Debug("Failed to export headers", "err", err)
} }
} }
+9 -10
View File
@@ -4,9 +4,9 @@ package goirsdk
import ( import (
"fmt" "fmt"
"io" "io"
"log/slog"
"os" "os"
"github.com/ESilva15/goirsdk/logger"
"github.com/ESilva15/goirsdk/mmaputils" "github.com/ESilva15/goirsdk/mmaputils"
"github.com/ESilva15/goirsdk/sharedMem" "github.com/ESilva15/goirsdk/sharedMem"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@@ -33,6 +33,7 @@ const (
) )
type Options struct { type Options struct {
Logger *slog.Logger
SourceType TelemetryContainer // type of source data SourceType TelemetryContainer // type of source data
SourcePath string // Path to source SourcePath string // Path to source
IBTExportType TelemetryContainer // export type of telemetry: store .ibt or replay in shm IBTExportType TelemetryContainer // export type of telemetry: store .ibt or replay in shm
@@ -75,11 +76,9 @@ func (i *IBT) IsConnected() bool {
} }
func (i *IBT) exportYAML() error { func (i *IBT) exportYAML() error {
log := logger.GetInstance()
file, err := os.OpenFile(i.Opts.SessionInfoExportPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644) file, err := os.OpenFile(i.Opts.SessionInfoExportPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil { if err != nil {
log.Printf("Failed to open file for YAML export: %v\n", err) i.Opts.Logger.Debug(fmt.Sprintf("Failed to open file for YAML export: %v\n", err))
return fmt.Errorf("failed to open output file for YAML: %v", err) return fmt.Errorf("failed to open output file for YAML: %v", err)
} }
defer file.Close() defer file.Close()
@@ -88,7 +87,7 @@ func (i *IBT) exportYAML() error {
err = enc.Encode(i.SessionInfo) err = enc.Encode(i.SessionInfo)
if err != nil { if err != nil {
log.Printf("Failed to write into file for YAML export: %v\n", err) i.Opts.Logger.Debug(fmt.Sprintf("Failed to write into file for YAML export: %v\n", err))
return fmt.Errorf("failed to write YAML contents to file: %v", err) return fmt.Errorf("failed to write YAML contents to file: %v", err)
} }
@@ -96,13 +95,11 @@ func (i *IBT) exportYAML() error {
} }
func (i *IBT) exportIBT(data []byte, offset int64) error { func (i *IBT) exportIBT(data []byte, offset int64) error {
log := logger.GetInstance()
_, err := i.IBTExporter.WriteAt(data, offset) _, err := i.IBTExporter.WriteAt(data, offset)
if err != nil { if err != nil {
i.IBTExporter.Close() i.IBTExporter.Close()
i.IBTExporter = nil i.IBTExporter = nil
log.Println("Won't attempt to export anymore") i.Opts.Logger.Debug(fmt.Sprintf("won't attempt to export anymore: %+v", err))
return err return err
} }
@@ -177,8 +174,6 @@ func (i *IBT) openExporter() error {
// Init serves to initialize and get a hold of a IBT struct // Init serves to initialize and get a hold of a IBT struct
// Receives an Options struct with the required configurations // Receives an Options struct with the required configurations
func Init(opts Options) (*IBT, error) { func Init(opts Options) (*IBT, error) {
// log := logger.GetInstance()
// Create our irsdk instance // Create our irsdk instance
var err error var err error
ibt := IBT{ ibt := IBT{
@@ -236,6 +231,10 @@ func (i *IBT) ListVariables() map[string]Var {
// Close cleans up our irsdk instance // Close cleans up our irsdk instance
func (i *IBT) Close() { func (i *IBT) Close() {
if i == nil {
return
}
if i.winUtils != nil { if i.winUtils != nil {
// If its not live data, the user is the one with ownership of the handle // If its not live data, the user is the one with ownership of the handle
i.File.Close() i.File.Close()
-23
View File
@@ -1,23 +0,0 @@
package logger
import (
"log"
"os"
"sync"
)
var l *log.Logger
var once sync.Once
func createLogger() {
l = log.New(os.Stdout, "[ibtReader] ", log.LstdFlags | log.Lshortfile)
}
func GetInstance() *log.Logger {
once.Do(func() {
createLogger()
})
return l
}
+1 -5
View File
@@ -6,8 +6,6 @@ import (
"log" "log"
"strings" "strings"
"github.com/ESilva15/goirsdk/logger"
"golang.org/x/text/encoding/charmap" "golang.org/x/text/encoding/charmap"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@@ -312,8 +310,6 @@ type Driver struct {
// readSessionInfo will read the session info yaml out of the telemetry data // readSessionInfo will read the session info yaml out of the telemetry data
func (i *IBT) readSessionInfo() error { func (i *IBT) readSessionInfo() error {
log := logger.GetInstance()
sessionInfoStringRaw := make([]byte, i.Headers.SessionInfoLength) sessionInfoStringRaw := make([]byte, i.Headers.SessionInfoLength)
_, err := i.File.ReadAt(sessionInfoStringRaw, int64(i.Headers.SessionInfoOffset)) _, err := i.File.ReadAt(sessionInfoStringRaw, int64(i.Headers.SessionInfoOffset))
if err != nil { if err != nil {
@@ -337,7 +333,7 @@ func (i *IBT) readSessionInfo() error {
if i.Opts.SessionInfoExport { if i.Opts.SessionInfoExport {
err := i.exportYAML() err := i.exportYAML()
if err != nil { if err != nil {
log.Printf("Failed to export YAML string: %v\n", err) i.Opts.Logger.Debug("Failed to export YAML string", "err", err)
} }
} }
+27 -18
View File
@@ -263,6 +263,10 @@ func (i *IBT) readData(buf []byte) error {
} }
// -------------- // --------------
if k == "SessionState" {
i.Opts.Logger.Debug(fmt.Sprintf("SessionState: %+v", v))
}
i.Vars.Vars[k] = v i.Vars.Vars[k] = v
} }
@@ -273,7 +277,8 @@ func (i *IBT) readData(buf []byte) error {
// live and offline data // live and offline data
func (i *IBT) Update(timeout time.Duration) (IRacingState, error) { func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
// This is what happens if we are reading live data // This is what happens if we are reading live data
if i.winUtils != nil { switch i.Opts.SourceType {
case SharedMemoryFile:
// Put a way to check if the sim is active here // Put a way to check if the sim is active here
// fmt.Println("NOT CHECKING IF SIM IS ACTIVE - ADD ME") // fmt.Println("NOT CHECKING IF SIM IS ACTIVE - ADD ME")
@@ -313,17 +318,19 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
if i.Opts.IBTExport { if i.Opts.IBTExport {
// Dirty attempt at getting this to work to write to a memory mapped file // Dirty attempt at getting this to work to write to a memory mapped file
var offset int64 = 0
switch i.Opts.IBTExportType { switch i.Opts.IBTExportType {
case IBTFile: case IBTFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset+i.Vars.RecorderTick*i.Headers.BufLen)) i.Opts.Logger.Debug("Reading live data and exporting to IBT file")
if err != nil { offset = int64(i.Headers.BufOffset + i.Vars.RecorderTick*i.Headers.BufLen)
log.Printf("Failed to export live telemetry data: %v", err)
}
case SharedMemoryFile: case SharedMemoryFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset)) i.Opts.Logger.Debug("Reading live data and exporting to SHM file")
if err != nil { offset = int64(i.Headers.BufOffset)
log.Printf("Failed to export live telemetry data: %v", err) }
}
err = i.exportIBT(buf, offset)
if err != nil {
i.Opts.Logger.Debug(fmt.Sprintf("Failed to export offline telemetry data: %+v", err))
} }
} }
@@ -338,7 +345,7 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
// Document why this is here, I don't remember the exact words right now // Document why this is here, I don't remember the exact words right now
i.Vars.RecorderTick++ i.Vars.RecorderTick++
} else { case IBTFile:
// This is what happens if we are reading from an .ibt file // This is what happens if we are reading from an .ibt file
// This will get the dataframe corresponding to a given tick // This will get the dataframe corresponding to a given tick
start := i.Headers.BufOffset + i.Vars.Tick*i.Headers.BufLen start := i.Headers.BufOffset + i.Vars.Tick*i.Headers.BufLen
@@ -349,17 +356,19 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
// writing to a file // writing to a file
if i.Opts.IBTExport { if i.Opts.IBTExport {
// Dirty attempt at getting this to work to write to a memory mapped file // Dirty attempt at getting this to work to write to a memory mapped file
var offset int64 = 0
switch i.Opts.IBTExportType { switch i.Opts.IBTExportType {
case IBTFile: case IBTFile:
err = i.exportIBT(buf, int64(start)) i.Opts.Logger.Debug("Reading IBT file and exporting to IBT file")
if err != nil { offset = int64(start)
log.Printf("Failed to export offline telemetry data: %v", err)
}
case SharedMemoryFile: case SharedMemoryFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset)) i.Opts.Logger.Debug("Reading IBT file and exporting to SHM file")
if err != nil { offset = int64(i.Headers.BufOffset)
log.Printf("Failed to export live telemetry data: %v", err) }
}
err = i.exportIBT(buf, offset)
if err != nil {
i.Opts.Logger.Debug(fmt.Sprintf("Failed to export offline telemetry data: %+v", err))
} }
} }