9 changed files with 617 additions and 280 deletions
+478 -148
View File
@@ -1,5 +1,9 @@
package goirsdk
import (
"log"
)
type Msg struct {
Cmd int
P1 int32
@@ -15,7 +19,6 @@ const (
IRSDK_BROADCASTMSGNAME string = "IRSDK_BROADCASTMSG"
fileMapSize uint32 = 1164 * 1024
connTimeout int64 = 30
stConnected int = 1
)
const (
@@ -112,163 +115,490 @@ const (
csFocusAtDriver int = 0 // ctFocusAtDriver + car number...
)
// Camera positions
// StatusField - START
const (
// CamNose
irsdk_stConnected = 0x01
)
// Some other constants that I need to get trough
// // bit fields
func (i *IBT) SessionStatusConnected() bool {
return i.Headers.Status == irsdk_stConnected
}
// NOTE: move this away from here
// func (i *IBT) SessionTimedOut() bool {
// return sdk.lastValidData+connTimeout > time.Now().Unix()
// }
// StatusField - END
// Camera positions
type bitfieldValue struct {
Value int
Name string
}
// EngineWarnings const
// EngineWarnings - Start
// TODO: wtf
var (
irsdkWaterTempWarning = bitfieldValue{0x01, "irsdk_waterTempWarning"}
irsdkFuelPressureWarning = bitfieldValue{0x02, "irsdk_fueldPressureWarning"}
irsdkOilPressureWarning = bitfieldValue{0x04, "irsdk_oilPressureWarning"}
irsdkEngineStalled = bitfieldValue{0x08, "irsdk_engineStalled"}
irsdkPitSpeedLimiter = bitfieldValue{0x10, "irsdk_pitSpeedLimiter"}
irsdkRevLimiterActive = bitfieldValue{0x20, "irsdk_revLimiterActive"}
irsdkAbsActive = bitfieldValue{0x100, "irsdk_absActive"}
irsdkEngineWarnings = []bitfieldValue{
irsdkWaterTempWarning, irsdkFuelPressureWarning,
irsdkOilPressureWarning, irsdkEngineStalled, irsdkPitSpeedLimiter, irsdkRevLimiterActive,
irsdkAbsActive,
}
irsdk_WaterTempWarning = 0x00000001
irsdk_FuelPressureWarning = 0x00000002
irsdk_OilPressureWarning = 0x00000004
irsdk_EngineStalled = 0x00000008
irsdk_PitSpeedLimiter = 0x00000010
irsdk_RevLimiterActive = 0x00000020
irsdk_AbsActive = 0x00000100
)
// enum irsdk_EngineWarnings
// {
// irsdk_waterTempWarning = 0x01,
// irsdk_fuelPressureWarning = 0x02,
// irsdk_oilPressureWarning = 0x04,
// irsdk_engineStalled = 0x08,
// irsdk_pitSpeedLimiter = 0x10,
// irsdk_revLimiterActive = 0x20,
// };
//
// // global flags
// enum irsdk_Flags
// {
// // global flags
// irsdk_checkered = 0x00000001,
// irsdk_white = 0x00000002,
// irsdk_green = 0x00000004,
// irsdk_yellow = 0x00000008,
// irsdk_red = 0x00000010,
// irsdk_blue = 0x00000020,
// irsdk_debris = 0x00000040,
// irsdk_crossed = 0x00000080,
// irsdk_yellowWaving = 0x00000100,
// irsdk_oneLapToGreen = 0x00000200,
// irsdk_greenHeld = 0x00000400,
// irsdk_tenToGo = 0x00000800,
// irsdk_fiveToGo = 0x00001000,
// irsdk_randomWaving = 0x00002000,
// irsdk_caution = 0x00004000,
// irsdk_cautionWaving = 0x00008000,
//
// // drivers black flags
// irsdk_black = 0x00010000,
// irsdk_disqualify = 0x00020000,
// irsdk_servicible = 0x00040000, // car is allowed service (not a flag)
// irsdk_furled = 0x00080000,
// irsdk_repair = 0x00100000,
//
// // start lights
// irsdk_startHidden = 0x10000000,
// irsdk_startReady = 0x20000000,
// irsdk_startSet = 0x40000000,
// irsdk_startGo = 0x80000000,
// };
//
//
// // status
// enum irsdk_TrkLoc
// {
// irsdk_NotInWorld = -1,
// irsdk_OffTrack,
// irsdk_InPitStall,
// irsdk_AproachingPits,
// irsdk_OnTrack
// };
//
// enum irsdk_TrkSurf
// {
// irsdk_SurfaceNotInWorld = -1,
// irsdk_UndefinedMaterial = 0,
//
// irsdk_Asphalt1Material,
// irsdk_Asphalt2Material,
// irsdk_Asphalt3Material,
// irsdk_Asphalt4Material,
// irsdk_Concrete1Material,
// irsdk_Concrete2Material,
// irsdk_RacingDirt1Material,
// irsdk_RacingDirt2Material,
// irsdk_Paint1Material,
// irsdk_Paint2Material,
// irsdk_Rumble1Material,
// irsdk_Rumble2Material,
// irsdk_Rumble3Material,
// irsdk_Rumble4Material,
//
// irsdk_Grass1Material,
// irsdk_Grass2Material,
// irsdk_Grass3Material,
// irsdk_Grass4Material,
// irsdk_Dirt1Material,
// irsdk_Dirt2Material,
// irsdk_Dirt3Material,
// irsdk_Dirt4Material,
// irsdk_SandMaterial,
// irsdk_Gravel1Material,
// irsdk_Gravel2Material,
// irsdk_GrasscreteMaterial,
// irsdk_AstroturfMaterial,
// };
//
// enum irsdk_SessionState
// {
// irsdk_StateInvalid,
// irsdk_StateGetInCar,
// irsdk_StateWarmup,
// irsdk_StateParadeLaps,
// irsdk_StateRacing,
// irsdk_StateCheckered,
// irsdk_StateCoolDown
// };
//
// enum irsdk_CameraState
// {
// irsdk_IsSessionScreen = 0x0001, // the camera tool can only be activated if viewing the session screen (out of car)
// irsdk_IsScenicActive = 0x0002, // the scenic camera is active (no focus car)
//
// //these can be changed with a broadcast message
// irsdk_CamToolActive = 0x0004,
// irsdk_UIHidden = 0x0008,
// irsdk_UseAutoShotSelection = 0x0010,
// irsdk_UseTemporaryEdits = 0x0020,
// irsdk_UseKeyAcceleration = 0x0040,
// irsdk_UseKey10xAcceleration = 0x0080,
// irsdk_UseMouseAimMode = 0x0100
// };
//
// enum irsdk_PitSvFlags
// {
// irsdk_LFTireChange = 0x0001,
// irsdk_RFTireChange = 0x0002,
// irsdk_LRTireChange = 0x0004,
// irsdk_RRTireChange = 0x0008,
//
// irsdk_FuelFill = 0x0010,
// irsdk_WindshieldTearoff = 0x0020,
// irsdk_FastRepair = 0x0040
// };
func (i *IBT) checkEngineWarningsBitfield(field int) bool {
val, ok := i.Vars.Vars["EngineWarnings"]
if !ok {
log.Fatal("no EngineWarnings")
}
//----
//
bitfield, ok := val.Value.(uint32)
if !ok {
log.Fatalf("unable to typecast EngineWarnings: %+v", val)
}
return bitfield&uint32(field) != 0
}
func (i *IBT) WaterTempWarning() bool {
return i.checkEngineWarningsBitfield(irsdk_WaterTempWarning)
}
func (i *IBT) FuelPressureWarning() bool {
return i.checkEngineWarningsBitfield(irsdk_FuelPressureWarning)
}
func (i *IBT) OilPressureWarning() bool {
return i.checkEngineWarningsBitfield(irsdk_OilPressureWarning)
}
func (i *IBT) EngineStalled() bool {
return i.checkEngineWarningsBitfield(irsdk_EngineStalled)
}
func (i *IBT) PitSpeedLimiter() bool {
return i.checkEngineWarningsBitfield(irsdk_PitSpeedLimiter)
}
func (i *IBT) RevLimiterActive() bool {
return i.checkEngineWarningsBitfield(irsdk_RevLimiterActive)
}
func (i *IBT) AbsActive() bool {
return i.checkEngineWarningsBitfield(irsdk_AbsActive)
}
// EngineWarnings - END
// SessionState - START
const (
irsdk_StateInvalid = 0x00
irsdk_StateGetInCar = 0x01
irsdk_StateWarmup = 0x02
irsdk_StateParadeLaps = 0x03
irsdk_StateRacing = 0x04
irsdk_StateCheckered = 0x05
irsdk_StateCoolDown = 0x06
)
func (i *IBT) checkSessionStateField(field int) bool {
val, ok := i.Vars.Vars["SessionState"]
if !ok {
return true
}
value, ok := val.Value.(int)
if !ok {
return true
}
return value == field
}
func (i *IBT) SessionStateInvalid() bool {
return i.checkSessionStateField(irsdk_StateInvalid)
}
// BUG: Need to fix all of these functions, they are all wrong
func (i *IBT) SessionStateGetInCar() bool {
return i.checkSessionStateField(irsdk_StateGetInCar)
}
func (i *IBT) SessionStateWarmup() bool {
return i.checkSessionStateField(irsdk_StateWarmup)
}
func (i *IBT) SessionStateParadeLaps() bool {
return i.checkSessionStateField(irsdk_StateParadeLaps)
}
func (i *IBT) SessionStateRacing() bool {
return i.checkSessionStateField(irsdk_StateRacing)
}
func (i *IBT) SessionStateCheckered() bool {
return i.checkSessionStateField(irsdk_StateCheckered)
}
func (i *IBT) SessionStateCoolDown() bool {
return i.checkSessionStateField(irsdk_StateCoolDown)
}
func SessionStateToString(state int) string {
switch state {
case irsdk_StateInvalid:
return "StateInvalid"
case irsdk_StateGetInCar:
return "StateGetInCar"
case irsdk_StateWarmup:
return "StateWarmup"
case irsdk_StateParadeLaps:
return "StateParadeLaps"
case irsdk_StateRacing:
return "StateRacing"
case irsdk_StateCheckered:
return "StateCheckered"
case irsdk_StateCoolDown:
return "StateCoolDown"
default:
return "UknownSessionState"
}
}
// SessionState - END
// TrkLoc const
const (
irsdk_NotInWorld = -1
irsdk_OffTrack = 0
irsdk_InPitStall = 1
irsdk_AproachingPits = 2
irsdk_OnTrack = 3
)
func TrkLocToString(trkloc int) string {
switch trkloc {
case irsdk_NotInWorld:
return "NotInWorld"
case irsdk_OffTrack:
return "OffTrack"
case irsdk_InPitStall:
return "InPitStall"
case irsdk_AproachingPits:
return "AproachingPits"
case irsdk_OnTrack:
return "OnTrack"
default:
return "UknownTrackLocation"
}
}
// Flags
const (
irsdk_checkered = 0x00000001
irsdk_white = 0x00000002
irsdk_green = 0x00000004
irsdk_yellow = 0x00000008
irsdk_red = 0x00000010
irsdk_blue = 0x00000020
irsdk_debris = 0x00000040
irsdk_crossed = 0x00000080
irsdk_yellowWaving = 0x00000100
irsdk_oneLapToGreen = 0x00000200
irsdk_greenHeld = 0x00000400
irsdk_tenToGo = 0x00000800
irsdk_fiveToGo = 0x00001000
irsdk_randomWaving = 0x00002000
irsdk_caution = 0x00004000
irsdk_cautionWaving = 0x00008000
// drivers black flags
irsdk_black = 0x00010000
irsdk_disqualify = 0x00020000
irsdk_servicible = 0x00040000 // car is allowed service (not a flag)
irsdk_furled = 0x00080000
irsdk_repair = 0x00100000
// start lights
irsdk_startHidden = 0x10000000
irsdk_startReady = 0x20000000
irsdk_startSet = 0x40000000
irsdk_startGo = 0x80000000
)
func FlagToString(flag int) string {
switch flag {
case irsdk_checkered:
return "irsdk_checkered"
case irsdk_white:
return "irsdk_white"
case irsdk_green:
return "irsdk_green"
case irsdk_yellow:
return "irsdk_yellow"
case irsdk_red:
return "irsdk_red"
case irsdk_blue:
return "irsdk_blue"
case irsdk_debris:
return "irsdk_debris"
case irsdk_crossed:
return "irsdk_crossed"
case irsdk_yellowWaving:
return "irsdk_yellowWaving"
case irsdk_oneLapToGreen:
return "irsdk_oneLapToGreen"
case irsdk_greenHeld:
return "irsdk_greenHeld"
case irsdk_tenToGo:
return "irsdk_tenToGo"
case irsdk_fiveToGo:
return "irsdk_fiveToGo"
case irsdk_randomWaving:
return "irsdk_randomWaving"
case irsdk_caution:
return "irsdk_caution"
case irsdk_cautionWaving:
return "irsdk_cautionWaving"
case irsdk_black:
return "irsdk_black"
case irsdk_disqualify:
return "irsdk_disqualify"
case irsdk_servicible:
return "irsdk_servicible"
case irsdk_furled:
return "irsdk_furled"
case irsdk_repair:
return "irsdk_repair"
case irsdk_startHidden:
return "irsdk_startHidden"
case irsdk_startReady:
return "irsdk_startReady"
case irsdk_startSet:
return "irsdk_startSet"
case irsdk_startGo:
return "irsdk_startGo"
default:
return "UknownFlag"
}
}
// enum irsdk_TrkSurf
const (
irsdk_SurfaceNotInWorld = iota - 1
irsdk_UndefinedMaterial
irsdk_Asphalt1Material
irsdk_Asphalt2Material
irsdk_Asphalt3Material
irsdk_Asphalt4Material
irsdk_Concrete1Material
irsdk_Concrete2Material
irsdk_RacingDirt1Material
irsdk_RacingDirt2Material
irsdk_Paint1Material
irsdk_Paint2Material
irsdk_Rumble1Material
irsdk_Rumble2Material
irsdk_Rumble3Material
irsdk_Rumble4Material
irsdk_Grass1Material
irsdk_Grass2Material
irsdk_Grass3Material
irsdk_Grass4Material
irsdk_Dirt1Material
irsdk_Dirt2Material
irsdk_Dirt3Material
irsdk_Dirt4Material
irsdk_SandMaterial
irsdk_Gravel1Material
irsdk_Gravel2Material
irsdk_GrasscreteMaterial
irsdk_AstroturfMaterial
)
func TrkSurfToString(surface int) string {
switch surface {
case irsdk_SurfaceNotInWorld:
return "SurfaceNotInWorld"
case irsdk_UndefinedMaterial:
return "UndefinedMaterial"
case irsdk_Asphalt1Material:
return "Asphalt1Material"
case irsdk_Asphalt2Material:
return "Asphalt2Material"
case irsdk_Asphalt3Material:
return "Asphalt3Material"
case irsdk_Asphalt4Material:
return "Asphalt4Material"
case irsdk_Concrete1Material:
return "Concrete1Material"
case irsdk_Concrete2Material:
return "Concrete2Material"
case irsdk_RacingDirt1Material:
return "RacingDirt1Material"
case irsdk_RacingDirt2Material:
return "RacingDirt2Material"
case irsdk_Paint1Material:
return "Paint1Material"
case irsdk_Paint2Material:
return "Paint2Material"
case irsdk_Rumble1Material:
return "Rumble1Material"
case irsdk_Rumble2Material:
return "Rumble2Material"
case irsdk_Rumble3Material:
return "Rumble3Material"
case irsdk_Rumble4Material:
return "Rumble4Material"
case irsdk_Grass1Material:
return "Grass1Material"
case irsdk_Grass2Material:
return "Grass2Material"
case irsdk_Grass3Material:
return "Grass3Material"
case irsdk_Grass4Material:
return "Grass4Material"
case irsdk_Dirt1Material:
return "Dirt1Material"
case irsdk_Dirt2Material:
return "Dirt2Material"
case irsdk_Dirt3Material:
return "Dirt3Material"
case irsdk_Dirt4Material:
return "Dirt4Material"
case irsdk_SandMaterial:
return "SandMaterial"
case irsdk_Gravel1Material:
return "Gravel1Material"
case irsdk_Gravel2Material:
return "Gravel2Material"
case irsdk_GrasscreteMaterial:
return "GrasscreteMaterial"
case irsdk_AstroturfMaterial:
return "AstroturfMaterial"
default:
return "UknownTrackSurface"
}
}
// CameraState
const (
irsdk_IsSessionScreen = 0x0001 // the camera tool can only be activated if viewing the session screen (out of car)
irsdk_IsScenicActive = 0x0002 // the scenic camera is active (no focus car)
// these can be changed with a broadcast message
irsdk_CamToolActive = 0x0004
irsdk_UIHidden = 0x0008
irsdk_UseAutoShotSelection = 0x0010
irsdk_UseTemporaryEdits = 0x0020
irsdk_UseKeyAcceleration = 0x0040
irsdk_UseKey10xAcceleration = 0x0080
irsdk_UseMouseAimMode = 0x0100
)
func CameraStateToString(state int) string {
switch state {
case irsdk_IsSessionScreen:
return "IsSessionScreen"
case irsdk_IsScenicActive:
return "IsScenicActive"
case irsdk_CamToolActive:
return "CamToolActive"
case irsdk_UIHidden:
return "UIHidden"
case irsdk_UseAutoShotSelection:
return "UseAutoShotSelection"
case irsdk_UseTemporaryEdits:
return "UseTemporaryEdits"
case irsdk_UseKeyAcceleration:
return "UseKeyAcceleration"
case irsdk_UseKey10xAcceleration:
return "UseKey10xAcceleration"
case irsdk_UseMouseAimMode:
return "UseMouseAimMode"
default:
return "UknownCameraState"
}
}
// PitSvFlags -- Start
const (
// Tires
irsdk_LFTireChange uint32 = 0x00000001
irsdk_RFTireChange uint32 = 0x00000002
irsdk_LRTireChange uint32 = 0x00000004
irsdk_RRTireChange uint32 = 0x00000008
// Fuel
irsdk_FuelFill uint32 = 0x00000010
irsdk_WindshieldTearoff uint32 = 0x00000020
irsdk_FastRepair uint32 = 0x00000040
// Other pit service request flags
irsdk_ClearTires uint32 = 0x00000080 // Uncheck tire change
irsdk_ClearWS uint32 = 0x00000100 // Uncheck windshield tearoff
irsdk_ClearFR uint32 = 0x00000200 // Uncheck FastRepair
irsdk_ClearFuel uint32 = 0x00000400 // Uncheck refuelling
)
func (i *IBT) checkPitSvFlags(field uint32) bool {
val, ok := i.Vars.Vars["PitSvFlags"]
if !ok {
log.Fatal("no PitSvFlags")
}
bitfield, ok := val.Value.(uint32)
if !ok {
log.Fatal("unable to get PitSvFlags: %+v", val)
}
return bitfield&field != 0
}
func (i *IBT) LFTireChange() bool {
return i.checkPitSvFlags(irsdk_LFTireChange)
}
func (i *IBT) RFTireChange() bool {
return i.checkPitSvFlags(irsdk_RFTireChange)
}
func (i *IBT) LRTireChange() bool {
return i.checkPitSvFlags(irsdk_LRTireChange)
}
func (i *IBT) RRTireChange() bool {
return i.checkPitSvFlags(irsdk_RRTireChange)
}
func (i *IBT) FuelFill() bool {
return i.checkPitSvFlags(irsdk_FuelFill)
}
func (i *IBT) WindshieldTearoff() bool {
return i.checkPitSvFlags(irsdk_WindshieldTearoff)
}
func (i *IBT) FastRepair() bool {
return i.checkPitSvFlags(irsdk_FastRepair)
}
func (i *IBT) ClearTires() bool {
return i.checkPitSvFlags(irsdk_ClearTires)
}
func (i *IBT) ClearWS() bool {
return i.checkPitSvFlags(irsdk_ClearWS)
}
func (i *IBT) ClearFR() bool {
return i.checkPitSvFlags(irsdk_ClearFR)
}
func (i *IBT) ClearFuel() bool {
return i.checkPitSvFlags(irsdk_ClearFuel)
}
// PitSvFlags -- End
+1 -7
View File
@@ -4,8 +4,6 @@ import (
"bytes"
"encoding/binary"
"fmt"
"github.com/ESilva15/goirsdk/logger"
)
const (
@@ -23,8 +21,6 @@ type DiskSubHeader struct {
// readSubheader will read the subheader contents out of the telemetry data
func (i *IBT) readSubheader() error {
log := logger.GetInstance()
var subheaderRaw [SubHeaderSize]byte
_, err := i.File.ReadAt(subheaderRaw[:], HeaderSize)
if err != nil {
@@ -39,7 +35,7 @@ func (i *IBT) readSubheader() error {
if i.Opts.IBTExport {
err = i.exportIBT(subheaderRaw[:], HeaderSize)
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
// valuable
func parseTelemetrySubHeader(buf [SubHeaderSize]byte) (*DiskSubHeader, error) {
// utils.HexDump(buf[:])
dst := DiskSubHeader{}
err := binary.Read(bytes.NewBuffer(buf[:]), binary.LittleEndian, &dst)
if err != nil {
@@ -3,6 +3,8 @@ package main
import (
"fmt"
"log"
"log/slog"
"os"
"time"
"github.com/ESilva15/goirsdk"
@@ -13,10 +15,22 @@ func msToKph(v float32) int {
}
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
irsdk, err := goirsdk.Init(goirsdk.Options{
Logger: logger,
SourceType: goirsdk.IBTFile,
SourcePath: "../../../../testTelemetry/gt3_mustang_bathurst.ibt",
SourcePath: "../../../../testTelemetry/mx5_2016Okayama_full_2024_10_19_22_02_12.ibt",
IBTExportType: goirsdk.SharedMemoryFile,
IBTExportPath: "./exported.ibt",
IBTExport: true,
@@ -57,9 +71,35 @@ func main() {
gear := int32(irsdk.Vars.Vars["Gear"].Value.(int))
rpm := int32(irsdk.Vars.Vars["RPM"].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("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())
// fmt.Printf("Vars:\n")
// for _, v := range irsdk.ListVariables() {
// fmt.Printf("%+v\n", v.Name)
// }
// os.Exit(0)
<-mainLoopTicker.C
}
@@ -3,6 +3,8 @@ package main
import (
"fmt"
"log"
"log/slog"
"os"
"time"
"github.com/ESilva15/goirsdk"
@@ -13,8 +15,22 @@ func msToKph(v float32) int {
}
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
irsdk, err := goirsdk.Init(goirsdk.Options{
Logger: logger,
SourceType: goirsdk.SharedMemoryFile,
})
if err != nil {
@@ -53,9 +69,29 @@ func main() {
gear := int32(irsdk.Vars.Vars["Gear"].Value.(int))
rpm := int32(irsdk.Vars.Vars["RPM"].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("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
}
+1 -5
View File
@@ -4,8 +4,6 @@ import (
"bytes"
"encoding/binary"
"fmt"
"github.com/ESilva15/goirsdk/logger"
)
const (
@@ -32,8 +30,6 @@ type TelemetryHeaders struct {
// readHeader will read the header out of the telemetry data
func (i *IBT) readHeader() error {
log := logger.GetInstance()
var headerRaw [FileHeaderSize]byte
_, err := i.File.ReadAt(headerRaw[:], 0)
if err != nil {
@@ -48,7 +44,7 @@ func (i *IBT) readHeader() error {
if i.Opts.IBTExport {
err = i.exportIBT(headerRaw[:], 0)
if err != nil {
log.Printf("Failed to export headers: %v\n", err)
i.Opts.Logger.Debug("Failed to export headers", "err", err)
}
}
+27 -26
View File
@@ -4,9 +4,9 @@ package goirsdk
import (
"fmt"
"io"
"log/slog"
"os"
"github.com/ESilva15/goirsdk/logger"
"github.com/ESilva15/goirsdk/mmaputils"
"github.com/ESilva15/goirsdk/sharedMem"
"gopkg.in/yaml.v3"
@@ -33,6 +33,7 @@ const (
)
type Options struct {
Logger *slog.Logger
SourceType TelemetryContainer // type of source data
SourcePath string // Path to source
IBTExportType TelemetryContainer // export type of telemetry: store .ibt or replay in shm
@@ -44,15 +45,10 @@ type Options struct {
// IBT struct will hold the relevant data for a given IBT file
type IBT struct {
File Reader // Source of the data
Opts Options
// TODO: IBTExporter should be an interface because we need to support shm too
File Reader // Source of the data
Opts Options
IBTExporter Writer
// IBTExport *os.File // If set, it will export the IBT data to the file
// IBTExportPath string // Path for IBT export
// YAMLExport *os.File // If set, it will export the session YAML to the file
// YAMLExportPath string // Path for YAML export
winUtils *mmaputils.IRacingWinUtils // WinUtils gives access to the system utilities
winUtils *mmaputils.IRacingWinUtils // WinUtils gives access to the system utilities
// TODO: fragment this struct a little bit, for now I want to actually get
// stuff done so its enough to work as is
@@ -64,24 +60,25 @@ type IBT struct {
}
func (i *IBT) IsConnected() bool {
if i.Headers != nil {
if sessionStatusOK(int(i.Headers.Status)) {
return true
}
// if sessionStatusOK(int(i.Headers.Status)) && (sdk.lastValidData+connTimeout > time.Now().Unix()) {
// return true
// }
if i.Headers == nil {
return false
}
return false
if !i.SessionStatusConnected() {
return false
}
if i.SessionStateInvalid() {
return false
}
return true
}
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)
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)
}
defer file.Close()
@@ -90,7 +87,7 @@ func (i *IBT) exportYAML() error {
err = enc.Encode(i.SessionInfo)
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)
}
@@ -98,13 +95,11 @@ func (i *IBT) exportYAML() error {
}
func (i *IBT) exportIBT(data []byte, offset int64) error {
log := logger.GetInstance()
_, err := i.IBTExporter.WriteAt(data, offset)
if err != nil {
i.IBTExporter.Close()
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
}
@@ -179,8 +174,6 @@ func (i *IBT) openExporter() error {
// Init serves to initialize and get a hold of a IBT struct
// Receives an Options struct with the required configurations
func Init(opts Options) (*IBT, error) {
// log := logger.GetInstance()
// Create our irsdk instance
var err error
ibt := IBT{
@@ -232,8 +225,16 @@ func Init(opts Options) (*IBT, error) {
return &ibt, nil
}
func (i *IBT) ListVariables() map[string]Var {
return i.Vars.Vars
}
// Close cleans up our irsdk instance
func (i *IBT) Close() {
if i == nil {
return
}
if i.winUtils != nil {
// If its not live data, the user is the one with ownership of the handle
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 -10
View File
@@ -6,8 +6,6 @@ import (
"log"
"strings"
"github.com/ESilva15/goirsdk/logger"
"golang.org/x/text/encoding/charmap"
"gopkg.in/yaml.v3"
)
@@ -312,8 +310,6 @@ type Driver struct {
// readSessionInfo will read the session info yaml out of the telemetry data
func (i *IBT) readSessionInfo() error {
log := logger.GetInstance()
sessionInfoStringRaw := make([]byte, i.Headers.SessionInfoLength)
_, err := i.File.ReadAt(sessionInfoStringRaw, int64(i.Headers.SessionInfoOffset))
if err != nil {
@@ -337,7 +333,7 @@ func (i *IBT) readSessionInfo() error {
if i.Opts.SessionInfoExport {
err := i.exportYAML()
if err != nil {
log.Printf("Failed to export YAML string: %v\n", err)
i.Opts.Logger.Debug("Failed to export YAML string", "err", err)
}
}
@@ -370,11 +366,6 @@ func parseSessionInfo(buf []byte, len int32) (*SessionInfoYAML, error) {
return &sessionInfo, nil
}
// sessionStatusOK will tell us if we are connected to the live data
func sessionStatusOK(status int) bool {
return (status & stConnected) > 0
}
// ToString will return a readable string of the struct
func (s *SessionInfoYAML) ToString() string {
stringified, _ := json.MarshalIndent(s, "", " ")
+30 -58
View File
@@ -7,7 +7,6 @@ import (
"io"
"log"
"math"
"strconv"
"strings"
"time"
)
@@ -157,38 +156,6 @@ func (i *IBT) readVariablerHeaders() error {
return nil
}
func (i *IBT) parseEngineWarnings() {
val, ok := i.Vars.Vars["EngineWarnings"]
if !ok {
log.Fatal("no engine warnings")
}
bitfield, err := strconv.ParseInt(val.Value.(string), 0, 64)
if err != nil {
log.Fatal("Unable to get engine warnings: " + err.Error())
}
for _, ew := range irsdkEngineWarnings {
result := (int(bitfield) & ew.Value) != 0
i.Vars.Vars[ew.Name] = Var{Value: result}
}
}
// parseBitfieldVariables will parse the variables:
// - irsdk_CameraState "CamCameraState"
// - irsdk_EngineWarnings "EngineWarnings"
// - irsdk_PitSvFlags "PitSvFlags"
// - irsdk_Flags "SessionFlags"
// - irsdk_SessionState "SessionState"
// - irsdk_TrkLoc "CarIdxTrackSurface"
//
// The approach for now will be to create unique entries in the data map for
// the fields in these variables
func (i *IBT) parseBitfieldVariables() {
// Parse the EngineWarnings variables - its the only one for now
i.parseEngineWarnings()
}
func (i *IBT) readData(buf []byte) error {
for k, v := range i.Vars.Vars {
// Slice of the variable value in the buffer
@@ -249,18 +216,17 @@ func (i *IBT) readData(buf []byte) error {
case IRSDK_bitField:
if v.Count > 1 {
// Array of data
data := make([]string, v.Count)
data := make([]uint32, v.Count)
for entry := 0; entry < int(v.Count); entry++ {
entryOffset := v.Offset + int32(entry)*int32(VarTypes[int(v.Type)].Size)
rbuf := buf[entryOffset : entryOffset+int32(VarTypes[int(v.Type)].Size)]
newValue := fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
data[entry] = newValue
data[entry] = binary.LittleEndian.Uint32(rbuf)
}
v.Value = data
} else {
// Single value
v.Value = fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
v.Value = binary.LittleEndian.Uint32(rbuf)
}
case IRSDK_float:
if v.Count > 1 {
@@ -297,12 +263,13 @@ func (i *IBT) readData(buf []byte) error {
}
// --------------
if k == "SessionState" {
i.Opts.Logger.Debug(fmt.Sprintf("SessionState: %+v", v))
}
i.Vars.Vars[k] = v
}
// Parse the bitfield variables here
i.parseBitfieldVariables()
return nil
}
@@ -310,7 +277,8 @@ func (i *IBT) readData(buf []byte) error {
// live and offline data
func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
// 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
// fmt.Println("NOT CHECKING IF SIM IS ACTIVE - ADD ME")
@@ -350,17 +318,19 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
if i.Opts.IBTExport {
// Dirty attempt at getting this to work to write to a memory mapped file
var offset int64 = 0
switch i.Opts.IBTExportType {
case IBTFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset+i.Vars.RecorderTick*i.Headers.BufLen))
if err != nil {
log.Printf("Failed to export live telemetry data: %v", err)
}
i.Opts.Logger.Debug("Reading live data and exporting to IBT file")
offset = int64(i.Headers.BufOffset + i.Vars.RecorderTick*i.Headers.BufLen)
case SharedMemoryFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset))
if err != nil {
log.Printf("Failed to export live telemetry data: %v", err)
}
i.Opts.Logger.Debug("Reading live data and exporting to SHM file")
offset = int64(i.Headers.BufOffset)
}
err = i.exportIBT(buf, offset)
if err != nil {
i.Opts.Logger.Debug(fmt.Sprintf("Failed to export offline telemetry data: %+v", err))
}
}
@@ -375,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
i.Vars.RecorderTick++
} else {
case IBTFile:
// This is what happens if we are reading from an .ibt file
// This will get the dataframe corresponding to a given tick
start := i.Headers.BufOffset + i.Vars.Tick*i.Headers.BufLen
@@ -386,17 +356,19 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
// writing to a file
if i.Opts.IBTExport {
// Dirty attempt at getting this to work to write to a memory mapped file
var offset int64 = 0
switch i.Opts.IBTExportType {
case IBTFile:
err = i.exportIBT(buf, int64(start))
if err != nil {
log.Printf("Failed to export offline telemetry data: %v", err)
}
i.Opts.Logger.Debug("Reading IBT file and exporting to IBT file")
offset = int64(start)
case SharedMemoryFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset))
if err != nil {
log.Printf("Failed to export live telemetry data: %v", err)
}
i.Opts.Logger.Debug("Reading IBT file and exporting to SHM file")
offset = int64(i.Headers.BufOffset)
}
err = i.exportIBT(buf, offset)
if err != nil {
i.Opts.Logger.Debug(fmt.Sprintf("Failed to export offline telemetry data: %+v", err))
}
}