29 Commits
Author SHA1 Message Date
esilva 4762d854cd drain the semaphores otherwise they will persist 2026-09-12 18:24:23 +01:00
esilva a82caa05a2 Fixed the evutils assignment
I will still have to look and clean this all up but I need to make it
work
2026-09-12 15:34:22 +01:00
esilva eed8c562b2 added events to signal fresh data 2026-09-12 14:39:48 +01:00
esilva 052f4582c9 The logger needs to be passed from the caller now - will change this in the future 2026-09-10 15:13:42 +01:00
esilva 7584b0ffcf fixing the bitfields 2026-09-08 17:11:07 +01:00
esilva 7a210af58d Fix the stateinvalid logic 2026-09-08 16:02:38 +01:00
esilva 78ec6a1e86 This is not pretty 2026-09-08 15:52:49 +01:00
esilva 6070620713 hammer a stupid fix 2026-09-08 15:48:44 +01:00
esilva 1ad9dd4ab7 IsConnected logic 2026-09-08 15:41:44 +01:00
esilva 56c7081e8f Merge pull request 'Added functions to check the session state' (#5) from bitfields-values into master
Reviewed-on: #5
2026-09-08 10:52:16 +01:00
esilva ddfcd31b27 Added functions to check the session state 2026-09-08 10:51:56 +01:00
esilva 18233a87b1 Merge pull request 'Added some of the bitfield' (#4) from bitfields-values into master
Reviewed-on: #4
2026-09-08 10:34:31 +01:00
esilva b9c013ae2f Added some of the bitfield
There's still work to do regarding this.
2026-09-08 10:33:26 +01:00
esilva 5f18023f13 Merge pull request 'Data handling improvement' (#1) from data-handling-improvement into master
Reviewed-on: #1
2026-08-24 11:01:06 +01:00
esilva 6b0283b206 added these examples
I'm using them for development...
2026-08-23 23:53:14 +01:00
esilva a449ced75f Linux can now read from a shared memory map and the sdk can create it 2026-08-23 23:44:36 +01:00
esilva 9adc0a9456 upgrade to support writing to a memmap file 2026-08-23 22:56:14 +01:00
esilva 76a091b076 README note for future reference 2026-07-13 23:36:44 +01:00
esilva b703933f08 added abs active flag to engine warnings 2026-03-15 19:40:27 +00:00
esilva 6bcc0a1613 Parse EngineWarnings 2026-03-15 19:06:15 +00:00
esilva fa7f0b73ee Modified the test a bit, gonna just merge whatever I have now and do work on the ESDI instead 2025-01-16 23:41:42 +00:00
esilva c5ff9f95c9 Working on some standings 2025-01-16 20:18:05 +00:00
esilva 4713fc80eb Not much here 2025-01-15 14:28:03 +00:00
esilva f102d74311 Testing the multipleCount live variables 2025-01-15 11:38:33 +00:00
esilva 172fa4ff52 Formatting of the previous commit 2025-01-14 14:45:45 +00:00
esilva 90a0321e9f Docstrings and documentation 2025-01-14 14:29:46 +00:00
esilva 6b595fabb1 Fixed a call to the IBT exporter in the sessionInfo file 2025-01-07 21:54:41 +00:00
esilva 4a56d253e5 Refactor data reading and export 2025-01-07 18:36:31 +00:00
esilva a3418e0c95 Added a logger to be easier to differentiate on the output 2025-01-07 15:11:05 +00:00
18 changed files with 1892 additions and 474 deletions
+109 -8
View File
@@ -1,14 +1,115 @@
# TODO
- [x] Read live telemetry (from a live session or replay)
- [x] Read data from a stored `.ibt` file
- [x] Allow to export the data to an `.ibt` file
- [x] Allow to export the session info data to a `.yaml` file
- [ ] Make sure variables with multiple counts are correctly parsed and stored
- [ ] Correctly support and implement the bitFields data
- [ ] Add the message broadcasting system
- [ ] Explore a more convenient API for fetching the data for the SDK user. Also do some renamings
- [ ] Change the pattern in which the data is fetched from the telemetry and
how it is exported into `.ibt` files
# About # About
This project will be able to parse `.ibt` files, read live data from races and This project is a simple Go SDK for the popular iRacing racing simulator.
broadcast messages to the service. Its still not very mature at all, but after It has the capabilites to:
this commit I will turn it into a package instead and give it a stable API. - Read live data (live session or replay)
Will also put some examples then. - Read data from a `.ibt` telemetry file
It should run on Linux, MacOS and Windows. With the caveat that live sessions
only happen on Windows (that I know about), therefore Linux and MacOS can only
read data from telemetry files.
## The SDK ## Usage
I used various sources to develop and understand how `iRacing` works, and learn The SDK instance is created by calling `goirsdk.Init(Reader, exportTelem, exportYAML)`
a lot with it. Once I have matured this project a bit I will document its - `Reader` is a variable that implements the interface:
inner workings too. ```go
type Reader interface {
io.Reader
io.ReaderAt
io.ReadCloser
}
```
To read data from a `.ibt` file, the user should pass the `*os.File` of it, and
to read live telemetry the user should pass nil
- `exportTelem` should be an empty string if the user doesn't want to export
the data, otherwise pass a string with the path for the destination telemetry
file
- `exportYAML` is just like the exportTelem but for the session info `yaml` data
### Example
```go
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/ESilva15/goirsdk"
)
func msToKph(v float32) int {
return int((3600 * v) / 1000)
}
func main() {
// Open the data source file
file, err := os.Open("/path/to/ibtFile")
if err != nil {
log.Fatalf("Failed to open IBT file: %v", err)
}
// Instantiate our iRacing SDK instance
irsdk, err := goirsdk.Init(file, "", "")
if err != nil {
log.Fatalf("Failed to create iRacing interface: %v", err)
}
defer irsdk.Close()
// Set up a loop to iterate our data
mainLoopTicker := time.NewTicker(time.Second / 60)
defer mainLoopTicker.Stop()
for {
// Update the data that the SDK is holding with the next tick
_, err := irsdk.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 := irsdk.Vars.Vars["Gear"]; !ok {
log.Fatal("Field `Gear` doesn't exist")
}
if _, ok := irsdk.Vars.Vars["RPM"]; !ok {
log.Fatal("Field `RPM` doesn't exist")
}
if _, ok := irsdk.Vars.Vars["Speed"]; !ok {
log.Fatal("Field `Speed` doesn't exist")
}
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)))
fmt.Printf("\033[?25l\033[2J\033[H")
fmt.Printf("Gear: %d, RPM: %d, Speed: %d", gear, rpm, speed)
<-mainLoopTicker.C
}
}
```
## SharedMem ## SharedMem
+493 -139
View File
@@ -1,5 +1,9 @@
package goirsdk package goirsdk
import (
"log"
)
type Msg struct { type Msg struct {
Cmd int Cmd int
P1 int32 P1 int32
@@ -8,13 +12,15 @@ type Msg struct {
} }
const ( const (
DATAVALIDEVENTNAME string = "IRSDKDataValidEvent"
MEMMAPFILENAME = "IRSDKMemMapFileName"
SimStatusUrl string = "http://127.0.0.1:32034/get_sim_status?object=simStatus" SimStatusUrl string = "http://127.0.0.1:32034/get_sim_status?object=simStatus"
IRSDK_DATAVALIDEVENTNAME string = "Local\\IRSDKDataValidEvent" IRSDK_DATAVALIDEVENTNAME string = "Local\\" + DATAVALIDEVENTNAME
IRSDK_MEMMAPFILENAME string = "Local\\IRSDKMemMapFileName" // IRSDK_DATAVALIDEVENTNAME string = DATAVALIDEVENTNAME
IRSDK_BROADCASTMSGNAME string = "IRSDK_BROADCASTMSG" IRSDK_MEMMAPFILENAME string = "Local\\" + MEMMAPFILENAME
fileMapSize uint32 = 1164 * 1024 IRSDK_BROADCASTMSGNAME string = "IRSDK_BROADCASTMSG"
connTimeout int64 = 30 fileMapSize uint32 = 1164 * 1024
stConnected int = 1 connTimeout int64 = 30
) )
const ( const (
@@ -111,142 +117,490 @@ const (
csFocusAtDriver int = 0 // ctFocusAtDriver + car number... csFocusAtDriver int = 0 // ctFocusAtDriver + car number...
) )
// Camera positions // StatusField - START
const ( const (
// CamNose irsdk_stConnected = 0x01
) )
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 - Start
// TODO: wtf
var (
irsdk_WaterTempWarning = 0x00000001
irsdk_FuelPressureWarning = 0x00000002
irsdk_OilPressureWarning = 0x00000004
irsdk_EngineStalled = 0x00000008
irsdk_PitSpeedLimiter = 0x00000010
irsdk_RevLimiterActive = 0x00000020
irsdk_AbsActive = 0x00000100
)
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"
}
}
// Some other constants that I need to get trough
// // bit fields
// 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 // enum irsdk_TrkSurf
// { const (
// irsdk_SurfaceNotInWorld = -1, irsdk_SurfaceNotInWorld = iota - 1
// irsdk_UndefinedMaterial = 0, irsdk_UndefinedMaterial
// irsdk_Asphalt1Material
// irsdk_Asphalt1Material, irsdk_Asphalt2Material
// irsdk_Asphalt2Material, irsdk_Asphalt3Material
// irsdk_Asphalt3Material, irsdk_Asphalt4Material
// irsdk_Asphalt4Material, irsdk_Concrete1Material
// irsdk_Concrete1Material, irsdk_Concrete2Material
// irsdk_Concrete2Material, irsdk_RacingDirt1Material
// irsdk_RacingDirt1Material, irsdk_RacingDirt2Material
// irsdk_RacingDirt2Material, irsdk_Paint1Material
// irsdk_Paint1Material, irsdk_Paint2Material
// irsdk_Paint2Material, irsdk_Rumble1Material
// irsdk_Rumble1Material, irsdk_Rumble2Material
// irsdk_Rumble2Material, irsdk_Rumble3Material
// irsdk_Rumble3Material, irsdk_Rumble4Material
// irsdk_Rumble4Material, irsdk_Grass1Material
// irsdk_Grass2Material
// irsdk_Grass1Material, irsdk_Grass3Material
// irsdk_Grass2Material, irsdk_Grass4Material
// irsdk_Grass3Material, irsdk_Dirt1Material
// irsdk_Grass4Material, irsdk_Dirt2Material
// irsdk_Dirt1Material, irsdk_Dirt3Material
// irsdk_Dirt2Material, irsdk_Dirt4Material
// irsdk_Dirt3Material, irsdk_SandMaterial
// irsdk_Dirt4Material, irsdk_Gravel1Material
// irsdk_SandMaterial, irsdk_Gravel2Material
// irsdk_Gravel1Material, irsdk_GrasscreteMaterial
// irsdk_Gravel2Material, irsdk_AstroturfMaterial
// 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 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
+23 -2
View File
@@ -19,12 +19,33 @@ type DiskSubHeader struct {
RecordCount int32 // RecordCount holds the number of data frames RecordCount int32 // RecordCount holds the number of data frames
} }
// readSubheader will read the subheader contents out of the telemetry data
func (i *IBT) readSubheader() error {
var subheaderRaw [SubHeaderSize]byte
_, err := i.File.ReadAt(subheaderRaw[:], HeaderSize)
if err != nil {
return fmt.Errorf("failed to read disk subheaders from file: %v", err)
}
i.SubHeaders, err = parseTelemetrySubHeader(subheaderRaw)
if err != nil {
return fmt.Errorf("unable to parse disk subheaders from file: %v", err)
}
// Write to the output file - TODO add the check
if i.Opts.IBTExport {
err = i.exportIBT(subheaderRaw[:], HeaderSize)
if err != nil {
i.Opts.Logger.Debug("failed to export disksubheader", "err", err)
}
}
return nil
}
// parseTelemetrySubHeader will return a pointer to a DiskSubHeader variable // parseTelemetrySubHeader will return a pointer to a DiskSubHeader variable
// 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 {
+66
View File
@@ -0,0 +1,66 @@
// I should rename winutils to something else but what this package does
// is interface some windows stuff that we need for the:
// - Broadcast Channel
// - Valid Data Event windows thing
package mmaputils
import (
"io"
"time"
)
type Reader interface {
io.Reader
io.ReaderAt
io.ReadCloser
}
type EventUtils struct {
Utils *utils
}
func Init() (*EventUtils, error) {
u, err := newUtils()
if err != nil {
return nil, err
}
return &EventUtils{u}, nil
}
func (u *EventUtils) Close() {
if u.Utils == nil {
return
}
u.Utils.Close()
}
// OpenEvent will open the named windows event
func (u *EventUtils) OpenEvent(name string) error {
return u.Utils.OpenEvent(name)
}
// OpenBroadcastChannel will open the broadcast channel
func (u *EventUtils) OpenBroadcastChannel(name string) error {
return u.Utils.OpenBroadcastChannel(name)
}
// CheckValidDataEvent checks if our windows even is telling us we are good to go
func (u *EventUtils) CheckValidDataEvent(timeout time.Duration) bool {
return u.Utils.CheckValidDataEvent(timeout)
}
// SignalEvent triggers a frame pulse (used by mock servers and tests)
func (u *EventUtils) SignalEvent() error {
return u.Utils.SignalEvent()
}
// SignalEvent triggers a frame pulse (used by mock servers and tests)
func SignalEvent(name string) {
signalEvent(name)
}
// CleanupEvent cleans up event resources (used by mock servers and tests)
func CleanupEvent(name string) {
cleanupEvent(name)
}
+177
View File
@@ -0,0 +1,177 @@
//go:build linux && cgo
package mmaputils
/*
#include <semaphore.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <stdlib.h>
static inline void* open_posix_semaphore(const char* name) {
sem_t* sem = sem_open(name, O_CREAT, 0666, 0);
if (sem == SEM_FAILED) {
return NULL;
}
return (void*)sem;
}
static inline void close_posix_semaphore(void* sem_ptr) {
if (sem_ptr != NULL) {
sem_close((sem_t*)sem_ptr);
}
}
static inline int timed_wait_posix_semaphore(void* sem_ptr, long timeout_ms) {
if (sem_ptr == NULL) {
return -1;
}
sem_t* sem = (sem_t*)sem_ptr;
// Drain the semaphore
while (sem_trywait(sem) == 0) {}
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_ms / 1000;
ts.tv_nsec += (timeout_ms % 1000) * 1000000;
if (ts.tv_nsec >= 1000000000) {
ts.tv_sec += ts.tv_nsec / 1000000000;
ts.tv_nsec %= 1000000000;
}
int res;
do {
res = sem_timedwait(sem, &ts);
} while (res == -1 && errno == EINTR); // Retry if interrupted by Go GC/scheduler
return res;
}
static inline int signal_posix_semaphore(const char* name) {
if (name == NULL) {
return -1;
}
sem_t* sem = sem_open(name, 0);
if (sem == SEM_FAILED) {
return -1;
}
int res = sem_post(sem);
sem_close(sem);
return res;
}
static inline int post_posix_semaphore(void* sem_ptr) {
if (sem_ptr != NULL) {
return sem_post((sem_t*)sem_ptr);
}
return -1;
}
static inline int unlink_posix_semaphore(const char* name) {
if (name == NULL) {
return -1;
}
return sem_unlink(name);
}
*/
import "C"
import (
"fmt"
"strings"
"time"
"unsafe"
"github.com/ESilva15/goirsdk/sharedMem"
)
type utils struct {
semName string
sem unsafe.Pointer
}
func newUtils() (*utils, error) {
return &utils{}, nil
}
func (u *utils) Close() {
if u.sem != nil {
C.close_posix_semaphore(u.sem)
u.sem = nil
}
}
// OpenMemMap returns a Reader interface that can be used to read the data
// No need to encapsulate it
func OpenMemMap(name string, size uint32) (Reader, error) {
file, err := sharedMem.Open(name, size)
if err != nil {
return nil, fmt.Errorf("failed to open `%s` with err: %+v", name, err)
}
return file, nil
}
// OpenEvent creates or connects to a Unix socket for event signaling on Linux
func (u *utils) OpenEvent(eventName string) error {
u.semName = "/" + strings.TrimPrefix(eventName, "/")
cName := C.CString(u.semName)
defer C.free(unsafe.Pointer(cName))
sem := C.open_posix_semaphore(cName)
if sem == nil {
return fmt.Errorf("failed to open POSIX semaphore: %s", u.semName)
}
u.sem = sem
return nil
}
func (u *utils) OpenBroadcastChannel(name string) error {
// No-op or log stub on Linux
return nil
}
// CheckValidDataEvent waits for a pulse byte sent over the socket
func (u *utils) CheckValidDataEvent(timeout time.Duration) bool {
if u.sem == nil {
return false
}
ms := C.long(timeout.Milliseconds())
res := C.timed_wait_posix_semaphore(u.sem, ms)
return res == 0
}
func (u *utils) SendBroadcastMessage(id, p1, p2 uintptr) error {
return nil
}
func (u *utils) SignalEvent() error {
if u.sem == nil {
return fmt.Errorf("u.sem is not set")
}
C.post_posix_semaphore(u.sem)
return nil
}
func signalEvent(name string) {
semName := "/" + strings.TrimPrefix(name, "/")
cName := C.CString(semName)
defer C.free(unsafe.Pointer(cName))
C.signal_posix_semaphore(cName)
}
func cleanupEvent(name string) {
semName := "/" + strings.TrimPrefix(name, "/")
cName := C.CString(semName)
defer C.free(unsafe.Pointer(cName))
C.unlink_posix_semaphore(cName)
}
+202
View File
@@ -0,0 +1,202 @@
package mmaputils_test
import (
"testing"
"time"
eventutils "github.com/ESilva15/goirsdk/eventutils"
)
const testEventName = "test_iRSDKDataValidEvent"
// Tests initialization and resource cleanup
func TestInitAndClose(t *testing.T) {
sdkUtils, err := eventutils.Init()
if err != nil {
t.Fatalf("Init() failed: %v", err)
}
if sdkUtils == nil {
t.Fatalf("Init() returned nil struct")
}
sdkUtils.Close()
}
// Tests timeout behavior when telemetry stalls or stops
func TestCheckValidDataEvent_Timeout(t *testing.T) {
defer eventutils.CleanupEvent(testEventName)
sdkUtils, err := eventutils.Init()
if err != nil {
t.Fatalf("Init() failed: %v", err)
}
defer sdkUtils.Close()
if err := sdkUtils.OpenEvent(testEventName); err != nil {
t.Fatalf("OpenEvent() failed: %v", err)
}
timeout := 40 * time.Millisecond
start := time.Now()
// Should return false because no producer signaled the event
got := sdkUtils.CheckValidDataEvent(timeout)
elapsed := time.Since(start)
if got != false {
t.Errorf("expected CheckValidDataEvent to return false on timeout, got true")
}
if elapsed < timeout {
t.Errorf("expected timeout to wait at least %v, returned early after %v", timeout, elapsed)
}
}
// Tests successful unblocking when a frame signal arrives
func TestCheckValidDataEvent_Signaled(t *testing.T) {
defer eventutils.CleanupEvent(testEventName)
sdkUtils, err := eventutils.Init()
if err != nil {
t.Fatalf("Init() failed: %v", err)
}
defer sdkUtils.Close()
if err := sdkUtils.OpenEvent(testEventName); err != nil {
t.Fatalf("OpenEvent() failed: %v", err)
}
// Simulate mock producer sending a frame signal after 10ms
go func() {
time.Sleep(10 * time.Millisecond)
eventutils.SignalEvent(testEventName)
}()
start := time.Now()
got := sdkUtils.CheckValidDataEvent(200 * time.Millisecond)
elapsed := time.Since(start)
if got != true {
t.Errorf("expected CheckValidDataEvent to return true on signal, got false")
}
if elapsed >= 150*time.Millisecond {
t.Errorf("CheckValidDataEvent took too long (%v), failed to wake up immediately", elapsed)
}
}
// Tests multi-frame streaming loop (simulating steady 60Hz feed)
func TestCheckValidDataEvent_MultipleTicks(t *testing.T) {
defer eventutils.CleanupEvent(testEventName)
sdkUtils, err := eventutils.Init()
if err != nil {
t.Fatalf("Init() failed: %v", err)
}
defer sdkUtils.Close()
if err := sdkUtils.OpenEvent(testEventName); err != nil {
t.Fatalf("OpenEvent() failed: %v", err)
}
frameCount := 5
go func() {
for i := 0; i < frameCount; i++ {
time.Sleep(10 * time.Millisecond)
eventutils.SignalEvent(testEventName)
}
}()
for i := 0; i < frameCount; i++ {
ok := sdkUtils.CheckValidDataEvent(100 * time.Millisecond)
if !ok {
t.Fatalf("failed to receive pulse for tick %d", i)
}
}
}
func Test60FPS60SecondsSemaphores(t *testing.T) {
if testing.Short() {
t.Skip("Skipping 60-second endurance test in short mode")
}
const eventName = "test_60fps_event"
const targetFPS = 60
const durationSeconds = 60
const totalFrames = targetFPS * durationSeconds // 3,600 frames
const frameInterval = time.Second / targetFPS // ~16.666ms
// Timeout per frame set to 100ms to absorb normal OS thread scheduling jitter
const frameWaitTimeout = 250 * time.Millisecond
// Cleanup prior event state
eventutils.CleanupEvent(eventName)
defer eventutils.CleanupEvent(eventName)
// Initialize Reader
uReader, err := eventutils.Init()
if err != nil {
t.Fatalf("Failed to initialize reader: %v", err)
}
defer uReader.Close()
if err := uReader.OpenEvent(eventName); err != nil {
t.Fatalf("Failed to open event on reader: %v", err)
}
// Initialize Writer
uWriter, err := eventutils.Init()
if err != nil {
t.Fatalf("Failed to initialize writer: %v", err)
}
defer uWriter.Close()
if err := uWriter.OpenEvent(eventName); err != nil {
t.Fatalf("Failed to open event on writer: %v", err)
}
stopWriter := make(chan struct{})
writerDone := make(chan struct{})
// Producer Goroutine: Emits pulse at 60 FPS
go func() {
defer close(writerDone)
ticker := time.NewTicker(frameInterval)
defer ticker.Stop()
for {
select {
case <-stopWriter:
return
case <-ticker.C:
if err := uWriter.SignalEvent(); err != nil {
t.Errorf("SignalEvent failed on writer: %v", err)
return
}
}
}
}()
startTime := time.Now()
receivedFrames := 0
// Consumer Loop: Consumes 3,600 frames continuously
for i := 1; i <= totalFrames; i++ {
ok := uReader.CheckValidDataEvent(frameWaitTimeout)
if !ok {
close(stopWriter)
<-writerDone
t.Fatalf("FAILED at frame %d/%d (elapsed: %v). Semaphore timed out after %v.",
i, totalFrames, time.Since(startTime), frameWaitTimeout)
}
receivedFrames++
}
elapsed := time.Since(startTime)
close(stopWriter)
<-writerDone
actualFPS := float64(receivedFrames) / elapsed.Seconds()
t.Logf("Passed: Processed %d/%d frames continuously in %v (Average FPS: %.2f)",
receivedFrames, totalFrames, elapsed, actualFPS)
}
@@ -1,13 +1,15 @@
//go:build windows && cgo //go:build windows
// +build windows,cgo
package winutils package mmaputils
import ( import (
"fmt"
"sync" "sync"
"syscall"
"time" "time"
"unsafe" "unsafe"
"github.com/ESilva15/goirsdk/sharedMem"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
) )
@@ -16,13 +18,11 @@ const (
WAIT_TIMEOUT = 258 WAIT_TIMEOUT = 258
) )
var ( var once sync.Once
once sync.Once
)
type utils struct { type utils struct {
user32DLL *windows.LazyDLL user32DLL *windows.LazyDLL
wEvent *windows.Handle wEvent windows.Handle
wBroadcastChn uintptr wBroadcastChn uintptr
} }
@@ -34,11 +34,22 @@ func newUtils() (*utils, error) {
} }
func (u *utils) Close() { func (u *utils) Close() {
closeEvent(u.wEvent) closeEvent(&u.wEvent)
// Do we need to unload the user32DLL ??? // Do we need to unload the user32DLL ???
// Do we need to close the broadcast channel ??? // Do we need to close the broadcast channel ???
} }
// OpenMemMap returns a Reader interface that can be used to read the data
// No need to encapsulate it
func OpenMemMap(name string, size uint32) (Reader, error) {
file, err := sharedMem.Open("Local\\"+name, size)
if err != nil {
return nil, err
}
return file, nil
}
// openEvent opens a windows.Handle for a given event // openEvent opens a windows.Handle for a given event
func (u *utils) OpenEvent(eventName string) error { func (u *utils) OpenEvent(eventName string) error {
name, err := windows.UTF16PtrFromString(eventName) name, err := windows.UTF16PtrFromString(eventName)
@@ -46,11 +57,16 @@ func (u *utils) OpenEvent(eventName string) error {
return err return err
} }
event, err := windows.OpenEvent(windows.SYNCHRONIZE, false, name) // Request EVENT_MODIFY_STATE so SetEvent can be called on this handle
event, err := windows.OpenEvent(windows.SYNCHRONIZE|windows.EVENT_MODIFY_STATE, false, name)
if err != nil { if err != nil {
return err // If event does not exist yet, create it
event, err = windows.CreateEvent(nil, 0, 0, name)
if err != nil {
return err
}
} }
u.wEvent = &event u.wEvent = event
return nil return nil
} }
@@ -78,6 +94,33 @@ func (u *utils) OpenBroadcastChannel(name string) error {
return nil return nil
} }
func (u *utils) SignalEvent() error {
if u.wEvent != 0 {
err := windows.SetEvent(u.wEvent)
if err != nil {
return fmt.Errorf("failed to signal Win32 event: %+v", err)
}
}
return nil
}
func signalEvent(name string) {
cName, err := syscall.UTF16PtrFromString(name)
if err != nil {
return
}
h, err := windows.OpenEvent(windows.EVENT_MODIFY_STATE, false, cName)
if err == nil {
windows.SetEvent(h)
windows.CloseHandle(h)
}
}
func cleanupEvent(name string) {
// Win32 events clean up automatically when handles close
}
// INITIALIZATION // INITIALIZATION
// closeEvent closes a given windows.Handle // closeEvent closes a given windows.Handle
@@ -90,7 +133,7 @@ func (u *utils) CheckValidDataEvent(timeout time.Duration) bool {
t0 := time.Now().UnixNano() t0 := time.Now().UnixNano()
timeoutInt := uint32(timeout / time.Millisecond) timeoutInt := uint32(timeout / time.Millisecond)
result, err := windows.WaitForSingleObject(*u.wEvent, timeoutInt) result, err := windows.WaitForSingleObject(u.wEvent, timeoutInt)
if err != nil { if err != nil {
remaining := timeoutInt - uint32((time.Now().UnixNano()-t0)/1000000) remaining := timeoutInt - uint32((time.Now().UnixNano()-t0)/1000000)
if remaining > 0 { if remaining > 0 {
@@ -0,0 +1,106 @@
package main
import (
"fmt"
"log"
"log/slog"
"os"
"time"
"github.com/ESilva15/goirsdk"
)
func msToKph(v float32) int {
return int((3600 * v) / 1000)
}
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/mx5_2016Okayama_full_2024_10_19_22_02_12.ibt",
IBTExportType: goirsdk.SharedMemoryFile,
IBTExportPath: "./exported.ibt",
IBTExport: true,
})
if err != nil {
log.Fatalf("Failed to create iRacing interface: %v", err)
}
defer irsdk.Close()
// Set up a loop to iterate our data
// TODO: revert this 240 back to 60 because i recorded the thing wrong or whatever
mainLoopTicker := time.NewTicker(time.Second / 240)
defer mainLoopTicker.Stop()
for {
// Update the data that the SDK is holding with the next tick
_, err := irsdk.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 := irsdk.Vars.Vars["Gear"]; !ok {
log.Fatal("Field `Gear` doesn't exist")
}
if _, ok := irsdk.Vars.Vars["RPM"]; !ok {
log.Fatal("Field `RPM` doesn't exist")
}
if _, ok := irsdk.Vars.Vars["Speed"]; !ok {
log.Fatal("Field `Speed` doesn't exist")
}
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\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
}
}
@@ -0,0 +1,98 @@
package main
import (
"fmt"
"log"
"log/slog"
"os"
"time"
"github.com/ESilva15/goirsdk"
)
func msToKph(v float32) int {
return int((3600 * v) / 1000)
}
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 {
log.Fatalf("Failed to create iRacing interface: %v", err)
}
defer irsdk.Close()
// Set up a loop to iterate our data
// TODO: revert this 240 back to 60 because i recorded the thing wrong or whatever
mainLoopTicker := time.NewTicker(time.Second / 240)
defer mainLoopTicker.Stop()
for {
// Update the data that the SDK is holding with the next tick
_, err := irsdk.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 := irsdk.Vars.Vars["Gear"]; !ok {
log.Fatal("Field `Gear` doesn't exist")
}
if _, ok := irsdk.Vars.Vars["RPM"]; !ok {
log.Fatal("Field `RPM` doesn't exist")
}
if _, ok := irsdk.Vars.Vars["Speed"]; !ok {
log.Fatal("Field `Speed` doesn't exist")
}
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\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
}
}
+10 -10
View File
@@ -1,10 +1,10 @@
module github.com/ESilva15/goirsdk module github.com/ESilva15/goirsdk
go 1.23.2 go 1.23.2
require ( require (
github.com/google/go-cmp v0.6.0 github.com/google/go-cmp v0.6.0
golang.org/x/sys v0.26.0 golang.org/x/sys v0.29.0
golang.org/x/text v0.19.0 golang.org/x/text v0.19.0
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
) )
+10 -10
View File
@@ -1,10 +1,10 @@
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 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/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 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 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 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 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 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=
+51 -39
View File
@@ -13,30 +13,58 @@ const (
// TelemetryHeaders struct to hold an IBT file's headers // TelemetryHeaders struct to hold an IBT file's headers
type TelemetryHeaders struct { type TelemetryHeaders struct {
Version int32 Version int32
// Status of 1 indicates a completed session and status of 0 a live session Status int32 // Status of 1 indicates a completed session and status of 0 a live session
Status int32 TickRate int32 // TickRate indicates the frequency of writes (usually 60)
// TickRate indicates the frequency of writes (usually 60) SessionInfoUpdate int32 // SessionInfoUpdate indicates the number of times the SessionInfo was
TickRate int32
// SessionInfoUpdate indicates the number of times the SessionInfo was
// updated. 0 for finished sessions and >1 for active sessions // updated. 0 for finished sessions and >1 for active sessions
SessionInfoUpdate int32 SessionInfoLength int32 // SessionInfoLength is the length of the session info buffer
// SessionInfoLength is the length of the session info buffer SessionInfoOffset int32 // SessionInfoOffset is the offset of the session info in the buffer
SessionInfoLength int32 NumVars int32 // NumVars is the number of variables in each input
// SessionInfoOffset is the offset of the session info in the buffer VarHeaderOffset int32 // VarHeaderOffset is the offset of the VarHeader
SessionInfoOffset int32 NumBuf int32 // NumBuf will be 1 for static files and 3 for live telemetry files
// NumVars is the number of variables in each input BufLen int32 // BufLen is the length for parsing VarHeader values
NumVars int32 Padding [12]byte // Padding
// VarHeaderOffset is the offset of the VarHeader BufOffset int32 // I still don't know what this is:
VarHeaderOffset int32 }
// NumBuf will be 1 for static files and 3 for live telemetry files
NumBuf int32 // readHeader will read the header out of the telemetry data
// BufLen is the length for parsing VarHeader values func (i *IBT) readHeader() error {
BufLen int32 var headerRaw [FileHeaderSize]byte
// Padding _, err := i.File.ReadAt(headerRaw[:], 0)
Padding [12]byte if err != nil {
// I still don't know what this is: return fmt.Errorf("failed to read headers from file: %v", err)
BufOffset int32 }
i.Headers, err = parseTelemetryHeader(headerRaw)
if err != nil {
return fmt.Errorf("unable to read headers from file: %v", err)
}
// Write to the output file - TODO: this should only write if necessary
if i.Opts.IBTExport {
err = i.exportIBT(headerRaw[:], 0)
if err != nil {
i.Opts.Logger.Debug("Failed to export headers", "err", err)
}
}
return nil
}
// parseTelemetryHeader will read the IBT file headers from a correctly sized
// buffer.
// You need to pass a the first FILE_HEADER_SIZE bytes of the buffer
func parseTelemetryHeader(buf [FileHeaderSize]byte) (*TelemetryHeaders, error) {
// utils.HexDump(buf[:])
// fmt.Printf("Len: %d\n", len(buf))
dst := TelemetryHeaders{}
err := binary.Read(bytes.NewBuffer(buf[:]), binary.LittleEndian, &dst)
if err != nil {
return nil, fmt.Errorf("unable to unpack data: %v", err)
}
return &dst, nil
} }
// ToString renders a string showing the values of the struct // ToString renders a string showing the values of the struct
@@ -61,19 +89,3 @@ func (th *TelemetryHeaders) ToString() string {
th.NumBuf, th.NumBuf, th.BufLen, th.BufLen, th.BufOffset, th.BufOffset, th.NumBuf, th.NumBuf, th.BufLen, th.BufLen, th.BufOffset, th.BufOffset,
) )
} }
// parseTelemetryHeader will read the IBT file headers from a correctly sized
// buffer.
// You need to pass a the first FILE_HEADER_SIZE bytes of the buffer
func parseTelemetryHeader(buf [FileHeaderSize]byte) (*TelemetryHeaders, error) {
// utils.HexDump(buf[:])
// fmt.Printf("Len: %d\n", len(buf))
dst := TelemetryHeaders{}
err := binary.Read(bytes.NewBuffer(buf[:]), binary.LittleEndian, &dst)
if err != nil {
return nil, fmt.Errorf("unable to unpack data: %v", err)
}
return &dst, nil
}
+188 -102
View File
@@ -3,23 +3,16 @@ package goirsdk
import ( import (
"fmt" "fmt"
"log"
"os"
"io" "io"
"log/slog"
"os"
"time"
"github.com/ESilva15/goirsdk/winutils" eventutils "github.com/ESilva15/goirsdk/eventutils"
"github.com/ESilva15/goirsdk/sharedMem"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
const (
ibtFile = "./telemetryFiles/mx5_2016Okayama_full_2024_10_19_22_02_12.ibt"
)
func msToKph(v float32) int {
return int((3600 * v) / 1000)
}
// Reader is an interface to represent the readable data that can be either // Reader is an interface to represent the readable data that can be either
// a .ibt file (or live data, hopefully) // a .ibt file (or live data, hopefully)
type Reader interface { type Reader interface {
@@ -28,35 +21,66 @@ type Reader interface {
io.ReadCloser io.ReadCloser
} }
type Writer interface {
io.WriterAt
io.Closer
}
type TelemetryContainer int
const (
IBTFile TelemetryContainer = iota
SharedMemoryFile TelemetryContainer = iota
)
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
IBTExportPath string // path where to export the data
IBTExport bool // whether to export the telemetry data
SessionInfoExport bool // whether to export the session info data
SessionInfoExportPath string // path where to export the session info
}
// IBT struct will hold the relevant data for a given IBT file // IBT struct will hold the relevant data for a given IBT file
type IBT struct { type IBT struct {
File Reader // Source of the data File Reader // Source of the data
FileToExport *os.File // If set, it will export the IBT data to the file Opts Options
YAMLExport *os.File // If set, it will export the session YAML to the file IBTExporter Writer
Headers *TelemetryHeaders // IBT file Headers winUtils *eventutils.EventUtils // WinUtils gives access to the system utilities
SubHeaders *DiskSubHeader // IBT file Sub Headers
SessionInfo *SessionInfoYAML // IBT file Session Info // TODO: fragment this struct a little bit, for now I want to actually get
Vars *TelemetryVars // Vars will hold the telemetry data // stuff done so its enough to work as is
winUtils *winutils.IRacingWinUtils // WinUtils gives access to the system utilities // Actual FILE
Headers *TelemetryHeaders // IBT file Headers
SubHeaders *DiskSubHeader // IBT file Sub Headers
SessionInfo *SessionInfoYAML // IBT file Session Info
Vars *TelemetryVars // Vars will hold the telemetry data
} }
func (i *IBT) IsConnected() bool { func (i *IBT) IsConnected() bool {
if i.Headers != nil { if i.Headers == nil {
if sessionStatusOK(int(i.Headers.Status)) { return false
return true
}
// if sessionStatusOK(int(i.Headers.Status)) && (sdk.lastValidData+connTimeout > time.Now().Unix()) {
// return true
// }
} }
return false if !i.SessionStatusConnected() {
return false
}
if i.SessionStateInvalid() {
return false
}
return true
} }
func (i *IBT) exportYAML(path string) { func (i *IBT) exportYAML() error {
file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) file, err := os.OpenFile(i.Opts.SessionInfoExportPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil { if err != nil {
log.Println("Failed to open output file for YAML: ", 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() defer file.Close()
@@ -64,122 +88,184 @@ func (i *IBT) exportYAML(path string) {
err = enc.Encode(i.SessionInfo) err = enc.Encode(i.SessionInfo)
if err != nil { if err != nil {
log.Println("Failed to print YAML to file: ", 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 nil
} }
// Init serves to initialize and get a hold of a IBT struct func (i *IBT) exportIBT(data []byte, offset int64) error {
func Init(f Reader, exportTelem string, exportYAML string) (*IBT, error) { nBytes, err := i.IBTExporter.WriteAt(data, offset)
// Read the header of the file if err != nil {
var err error i.IBTExporter.Close()
ibt := IBT{ i.IBTExporter = nil
File: f, i.Opts.Logger.Debug(fmt.Sprintf("won't attempt to export anymore: %+v", err))
FileToExport: nil, return err
YAMLExport: nil,
Vars: &TelemetryVars{},
winUtils: nil,
} }
// If requested to output to a telemetry file if nBytes > 0 {
if exportTelem != "" { // Send the event stating the data has been created
ibt.FileToExport, err = os.OpenFile(exportTelem, os.O_CREATE|os.O_RDWR, 0644) err = i.winUtils.Utils.SignalEvent()
if err != nil { if err != nil {
return nil, err i.Opts.Logger.Debug("failed to signal event", "err", err)
} else {
i.Opts.Logger.Debug("no error signaling", "nBytes", nBytes)
} }
ibt.FileToExport.Sync()
} }
if ibt.File == nil { return nil
}
func (i *IBT) openSource() error {
var err error
switch i.Opts.SourceType {
case SharedMemoryFile:
// User is requesting us to read live data - present in the mem map file // User is requesting us to read live data - present in the mem map file
ibt.File, err = winutils.OpenMemMap(IRSDK_MEMMAPFILENAME, fileMapSize) i.File, err = eventutils.OpenMemMap(MEMMAPFILENAME, fileMapSize)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to open memory mapped file: %v", err) return fmt.Errorf("failed to open memory mapped file: %+v", err)
} }
// To use our windows interface we need to initialize it first // To use our windows interface we need to initialize it first
// it will return a struct with a pointer to the windows handles // it will return a struct with a pointer to the windows handles
// if, for some reason, we need to stub out this to run in on Linux its easier // if, for some reason, we need to stub out this to run in on Linux its easier
ibt.winUtils, err = winutils.Init() // i.winUtils, err = eventutils.Init()
if err != nil { // if err != nil {
return nil, err // return err
} // }
// I don't believe we need this on windows either, but I'll have to check
// We need to open the windows event thing // We need to open the windows event thing
err = ibt.winUtils.OpenWinEvent(IRSDK_DATAVALIDEVENTNAME) // err = i.winUtils.OpenWinEvent(IRSDK_DATAVALIDEVENTNAME)
if err != nil { // if err != nil {
return nil, err // return err
} // }
// We need to open the broadcast channel // We need to open the broadcast channel
err = ibt.winUtils.OpenBroadcastChannel(IRSDK_BROADCASTMSGNAME) // err = i.winUtils.OpenBroadcastChannel(IRSDK_BROADCASTMSGNAME)
// if err != nil {
// return err
// }
case IBTFile:
i.File, err = os.Open(i.Opts.SourcePath)
if err != nil { if err != nil {
return nil, err return fmt.Errorf("failed to open file `%s`: %+v", i.Opts.SourcePath, err)
}
default:
return fmt.Errorf("a source type must be specified")
}
return nil
}
func (i *IBT) openExporter() error {
var err error
switch i.Opts.IBTExportType {
case SharedMemoryFile:
// Lets create a shared memory file!
shm, err := sharedMem.Create(MEMMAPFILENAME, fileMapSize)
if err != nil {
return fmt.Errorf("unable to create memory map file: %+v", err)
}
i.IBTExporter = shm
case IBTFile:
i.IBTExporter, err = os.OpenFile(i.Opts.IBTExportPath, os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return fmt.Errorf("failed to open ibt export file: %v", err)
}
}
return nil
}
// 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) {
// Create our irsdk instance
var err error
ibt := IBT{
Opts: opts,
Vars: &TelemetryVars{},
}
// Set up the event utils
evutils, err := eventutils.Init()
if err != nil {
return nil, err
}
err = evutils.OpenEvent(IRSDK_DATAVALIDEVENTNAME)
if err != nil {
return nil, err
}
ibt.winUtils = evutils
// Setup the source
err = ibt.openSource()
if err != nil {
return nil, err
}
// Setup the IBT data export - can be either shared memory or data file
if opts.IBTExport {
err = ibt.openExporter()
if err != nil {
// We log this only, or return some type of message
// Set the option to false so we won't export
ibt.Opts.IBTExport = false
} }
} }
// Read the file headers // Read the file headers
var headerRaw [FileHeaderSize]byte err = ibt.readHeader()
_, err = ibt.File.ReadAt(headerRaw[:], 0)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to read headers from file: %v", err) return nil, err
}
ibt.Headers, err = parseTelemetryHeader(headerRaw)
if err != nil {
return nil, fmt.Errorf("Unable to read headers from file: %v", err)
}
// Write to the output file
_, err = ibt.FileToExport.WriteAt(headerRaw[:], 0)
if err != nil {
log.Fatal(err)
} }
// Read the disk sub headers // Read the disk sub headers
var subheaderRaw [SubHeaderSize]byte err = ibt.readSubheader()
_, err = ibt.File.ReadAt(subheaderRaw[:], HeaderSize)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to read disk subheaders from file: %v", err) return nil, err
}
ibt.SubHeaders, err = parseTelemetrySubHeader(subheaderRaw)
if err != nil {
return nil, fmt.Errorf("Unable to parse disk subheaders from file: %v", err)
}
// Write to the output file
_, err = ibt.FileToExport.WriteAt(subheaderRaw[:], HeaderSize)
if err != nil {
log.Fatal(err)
} }
// Read session info string // Read session info string
sessionInfoStringRaw := make([]byte, ibt.Headers.SessionInfoLength) err = ibt.readSessionInfo()
_, err = ibt.File.ReadAt(sessionInfoStringRaw, int64(ibt.Headers.SessionInfoOffset))
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to read sessionInfoString from file: %v", err) return nil, err
}
// Write to the output file
_, err = ibt.FileToExport.WriteAt(sessionInfoStringRaw[:], int64(ibt.Headers.SessionInfoOffset))
if err != nil {
log.Fatal(err)
}
ibt.SessionInfo, err = parseSessionInfo(sessionInfoStringRaw, ibt.Headers.SessionInfoLength)
if err != nil {
return nil, fmt.Errorf("Unable to parse SessionInfoString from file: %v", err)
}
// Write to YAML output file
if exportYAML != "" {
ibt.exportYAML(exportYAML)
} }
// Read the telemetry vars info // Read the telemetry vars info
err = ibt.readVariablerHeaders() err = ibt.readVariablerHeaders()
if err != nil { if err != nil {
return nil, fmt.Errorf("Unable to parser variable headers from file: %v", err) return nil, fmt.Errorf("unable to parser variable headers from file: %v", err)
} }
return &ibt, nil return &ibt, nil
} }
func (i *IBT) ListVariables() map[string]Var {
return i.Vars.Vars
}
// CheckForDataEvent
// timeout is in ms
func (i *IBT) CheckForDataEvent(timeout time.Duration) bool {
if i.winUtils.CheckValidDataEvent(timeout) {
return true
}
return false
}
// 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()
+101
View File
@@ -0,0 +1,101 @@
package goirsdk
// import (
// "fmt"
// "log"
// "os"
// "sort"
// "testing"
// "time"
// )
//
// type StandingsLine struct {
// CarIdx int
// LapPct float32
// Lap int32
// DriverName string
// EstTime float32
// TimeBehind float32
// }
//
// func lapTimeRepresentation(t float32) string {
// if t < 0 {
// t = 0
// }
//
// wholeSeconds := int64(t)
// lapTime := time.Unix(wholeSeconds, int64((t-float32(wholeSeconds))*1e9))
//
// return lapTime.Format("04:05.000")
// }
//
// func TestFunctionality(t *testing.T) {
// input, err := os.Open("../../testTelemetry/supercars_race_watkins_glenn.ibt")
// if err != nil {
// t.Fatal("Was unable to prepare telemetry file for testing.")
// }
//
// i, _ := Init(input, "", "")
// defer i.Close()
//
// // Set up a loop to iterate our data
// mainLoopTicker := time.NewTicker(time.Second / 60)
// defer mainLoopTicker.Stop()
//
// for {
// // Update the data that the SDK is holding with the next tick
// _, err := i.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 := i.Vars.Vars["CarIdxPosition"]; !ok {
// log.Fatal("Field `CarIdxPosition` doesn't exist")
// }
// driversLapDistPct := i.Vars.Vars["CarIdxLapDistPct"].Value.([]float32)
// driversEstTime := i.Vars.Vars["CarIdxEstTime"].Value.([]float32)
// driversLap := i.Vars.Vars["CarIdxLap"].Value.([]int32)
// // driversBehind := i.Vars.Vars["CarIdxF2Time"].Value.([]float32)
//
// drivers := i.SessionInfo.DriverInfo.Drivers
// myIdx := i.SessionInfo.DriverInfo.DriverCarIdx
//
// standings := make([]StandingsLine, len(drivers))
//
// fmt.Printf("\033[?25l\033[2J\033[H")
// for k := range len(drivers) {
// if drivers[k].CarIsPaceCar == 1 || drivers[k].IsSpectator == 1 {
// continue
// }
//
// standings[k] = StandingsLine{
// CarIdx: k,
// LapPct: driversLapDistPct[k],
// DriverName: drivers[k].UserName,
// EstTime: driversEstTime[k],
// Lap: driversLap[k],
// TimeBehind: driversEstTime[myIdx],
// }
// }
//
// sort.Slice(standings, func(i int, j int) bool {
// if standings[i].Lap > int32(standings[j].Lap) {
// return true
// }
//
// return standings[i].LapPct >= standings[j].LapPct
// })
//
// fmt.Printf("%v\n", driversEstTime)
// // for p, v := range standings {
// // fmt.Printf("[%2d] %-30s %13f %13f\n",
// // p+1, v.DriverName, v.LapPct, driversEstTime[p] - driversEstTime[myIdx])
// // }
//
// <-mainLoopTicker.C
// }
// }
+33 -5
View File
@@ -2,6 +2,7 @@ package goirsdk
import ( import (
"encoding/json" "encoding/json"
"fmt"
"log" "log"
"strings" "strings"
@@ -307,6 +308,38 @@ type Driver struct {
TeamIncidentCount int `yaml:"TeamIncidentCount"` TeamIncidentCount int `yaml:"TeamIncidentCount"`
} }
// readSessionInfo will read the session info yaml out of the telemetry data
func (i *IBT) readSessionInfo() error {
sessionInfoStringRaw := make([]byte, i.Headers.SessionInfoLength)
_, err := i.File.ReadAt(sessionInfoStringRaw, int64(i.Headers.SessionInfoOffset))
if err != nil {
return fmt.Errorf("Failed to read sessionInfoString from file: %v", err)
}
// Write to the output file
if i.Opts.IBTExport {
err := i.exportIBT(sessionInfoStringRaw[:], int64(i.Headers.SessionInfoOffset))
if err != nil {
log.Printf("Failed to export offline telemetry data: %v", err)
}
}
i.SessionInfo, err = parseSessionInfo(sessionInfoStringRaw, i.Headers.SessionInfoLength)
if err != nil {
return fmt.Errorf("Unable to parse SessionInfoString from file: %v", err)
}
// Write to YAML output file
if i.Opts.SessionInfoExport {
err := i.exportYAML()
if err != nil {
i.Opts.Logger.Debug("Failed to export YAML string", "err", err)
}
}
return nil
}
// parseSessionInfo will parse the sessionInfo buffer into the SessionInfoYAML // parseSessionInfo will parse the sessionInfo buffer into the SessionInfoYAML
// struct // struct
func parseSessionInfo(buf []byte, len int32) (*SessionInfoYAML, error) { func parseSessionInfo(buf []byte, len int32) (*SessionInfoYAML, error) {
@@ -333,11 +366,6 @@ func parseSessionInfo(buf []byte, len int32) (*SessionInfoYAML, error) {
return &sessionInfo, nil 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 // ToString will return a readable string of the struct
func (s *SessionInfoYAML) ToString() string { func (s *SessionInfoYAML) ToString() string {
stringified, _ := json.MarshalIndent(s, "", " ") stringified, _ := json.MarshalIndent(s, "", " ")
+170 -35
View File
@@ -39,11 +39,13 @@ var (
} }
) )
type IRacingState int type (
type VarType struct { IRacingState int
Size int // Size is the var type size in bytes VarType struct {
Name string // Name is the irsdk var name Size int // Size is the var type size in bytes
} Name string // Name is the irsdk var name
}
)
type IBTVar struct { type IBTVar struct {
Type int32 Type int32
@@ -71,6 +73,20 @@ type Var struct {
Value interface{} Value interface{}
} }
func (v *Var) ToString() string {
return fmt.Sprintf(
"Type: %5d (0x%08x)\n"+
"Offset: %5d (0x%08x)\n"+
"Count: %5d (0x%08x)\n"+
"CountAsTime: %5t\n"+
"Name: %s\n"+
"Description: %s\n"+
"Unit: %s",
v.Type, v.Type, v.Offset, v.Offset, v.Count, v.Count,
v.CountAsTime, v.Name, v.Description, v.Unit,
)
}
func (v *IBTVar) ToString() string { func (v *IBTVar) ToString() string {
return fmt.Sprintf( return fmt.Sprintf(
"Type: %5d (0x%08x)\n"+ "Type: %5d (0x%08x)\n"+
@@ -91,9 +107,10 @@ type varBuffer struct {
} }
type TelemetryVars struct { type TelemetryVars struct {
Tick int32 // Keeps track of the current data buffer tick Tick int32 // Keeps track of the current data buffer tick
RecorderTick int32 // Counts from 0 when creating a telemetry file from a replay or live data RecorderTick int32 // Counts from 0 when creating a telemetry file from a
Vars map[string]Var // Variables content // replay or live data
Vars map[string]Var // Variables content
} }
func (i *IBT) readVariablerHeaders() error { func (i *IBT) readVariablerHeaders() error {
@@ -108,11 +125,13 @@ func (i *IBT) readVariablerHeaders() error {
return err return err
} }
_, err = i.FileToExport.WriteAt(rbuf, int64(i.Headers.VarHeaderOffset+k*VarHeaderSize)) if i.Opts.IBTExport {
if err != nil { err = i.exportIBT(rbuf, int64(i.Headers.VarHeaderOffset+k*VarHeaderSize))
log.Fatal(err) if err != nil {
// Don't outright kill it here - maybe nowhere else
log.Printf("Failed to export variable contents: %v\n", err)
}
} }
i.FileToExport.Sync()
var dst IBTVar var dst IBTVar
err = binary.Read(bytes.NewBuffer(rbuf[:]), binary.LittleEndian, &dst) err = binary.Read(bytes.NewBuffer(rbuf[:]), binary.LittleEndian, &dst)
@@ -145,19 +164,103 @@ func (i *IBT) readData(buf []byte) error {
// Read the value // Read the value
switch v.Type { switch v.Type {
case IRSDK_char: case IRSDK_char:
v.Value = string(rbuf[0]) if v.Count > 1 {
// Array of data
data := make([]string, 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 := string(rbuf[0])
data[entry] = newValue
}
v.Value = data
} else {
// Single value
v.Value = string(rbuf[0])
}
case IRSDK_bool: case IRSDK_bool:
v.Value = int(rbuf[0]) > 0 if v.Count > 1 {
// Array of data
data := make([]bool, 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 := int(rbuf[0]) > 0
data[entry] = newValue
}
v.Value = data
} else {
// Single value
v.Value = int(rbuf[0]) > 0
}
case IRSDK_int: case IRSDK_int:
v.Value = int(binary.LittleEndian.Uint32(rbuf)) if v.Count > 1 {
// Array of data
data := make([]int32, 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 := int32(binary.LittleEndian.Uint32(rbuf))
data[entry] = newValue
}
v.Value = data
} else {
// Single value
v.Value = int(binary.LittleEndian.Uint32(rbuf))
}
case IRSDK_bitField: case IRSDK_bitField:
v.Value = fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf))) if v.Count > 1 {
// Array of data
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)]
data[entry] = binary.LittleEndian.Uint32(rbuf)
}
v.Value = data
} else {
// Single value
v.Value = binary.LittleEndian.Uint32(rbuf)
}
case IRSDK_float: case IRSDK_float:
v.Value = math.Float32frombits(uint32(binary.LittleEndian.Uint32(rbuf))) if v.Count > 1 {
// Array of data
data := make([]float32, 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 := math.Float32frombits(uint32(binary.LittleEndian.Uint32(rbuf)))
data[entry] = newValue
}
v.Value = data
} else {
// Single value
v.Value = math.Float32frombits(uint32(binary.LittleEndian.Uint32(rbuf)))
}
case IRSDK_double: case IRSDK_double:
v.Value = math.Float64frombits(uint64(binary.LittleEndian.Uint64(rbuf))) if v.Count > 1 {
// Array of data
data := make([]float64, 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 := math.Float64frombits(uint64(binary.LittleEndian.Uint64(rbuf)))
data[entry] = newValue
}
v.Value = data
} else {
// Single value
v.Value = math.Float64frombits(uint64(binary.LittleEndian.Uint64(rbuf)))
}
} }
// --------------
i.Vars.Vars[k] = v i.Vars.Vars[k] = v
} }
@@ -165,8 +268,12 @@ func (i *IBT) readData(buf []byte) error {
return nil return nil
} }
// Update will read the next data chunk from the telemetry data, works for both the
// live and offline data
func (i *IBT) Update(timeout time.Duration) (IRacingState, error) { func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
if i.winUtils != nil { // This is what happens if we are reading live data
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")
@@ -200,13 +307,30 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
buf := make([]byte, i.Headers.BufLen) buf := make([]byte, i.Headers.BufLen)
_, err := i.File.ReadAt(buf, int64(start)) _, err := i.File.ReadAt(buf, int64(start))
if err == io.EOF {
return Ended, nil
}
if err != nil { if err != nil {
return Failed, err return Failed, err
} }
_, err = i.FileToExport.WriteAt(buf, int64(i.Headers.BufOffset+i.Vars.RecorderTick*i.Headers.BufLen)) if i.Opts.IBTExport {
if err != nil { // Dirty attempt at getting this to work to write to a memory mapped file
log.Fatalf("Failed to write to file [2]: %v", err) var offset int64 = 0
switch i.Opts.IBTExportType {
case IBTFile:
// 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:
// 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))
}
} }
err = i.readData(buf) err = i.readData(buf)
@@ -214,24 +338,15 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
return Unknown, err return Unknown, err
} }
if err == io.EOF { // Document why this is here, I don't remember the exact words right now
return Ended, nil
}
i.Vars.RecorderTick++ 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 // 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
buf := make([]byte, i.Headers.BufLen) buf := make([]byte, i.Headers.BufLen)
_, err := i.File.ReadAt(buf, int64(start)) _, err := i.File.ReadAt(buf, int64(start))
// Make this happen in a different thread, or have this send to a queue that has a thread
// writing to a file
_, err = i.FileToExport.WriteAt(buf, int64(start))
if err != nil {
log.Fatalf("Failed to write to file [1]: %v\n", err)
}
if err == io.EOF { if err == io.EOF {
return Ended, nil return Ended, nil
} }
@@ -239,6 +354,26 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
return Unknown, err return Unknown, err
} }
// Make this happen in a different thread, or have this send to a queue that has a thread
// 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:
// i.Opts.Logger.Debug("Reading IBT file and exporting to IBT file")
offset = int64(start)
case SharedMemoryFile:
// 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))
}
}
err = i.readData(buf) err = i.readData(buf)
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
log.Fatalf("What happened?\n%v\n", err) log.Fatalf("What happened?\n%v\n", err)
-59
View File
@@ -1,59 +0,0 @@
// I should rename winutils to something else but what this package does
// is interface some windows stuff that we need for the:
// - Broadcast Channel
// - Valid Data Event windows thing
package winutils
import (
"github.com/ESilva15/goirsdk/sharedMem"
"io"
"time"
)
type Reader interface {
io.Reader
io.ReaderAt
io.ReadCloser
}
type IRacingWinUtils struct {
Utils *utils
}
func Init() (*IRacingWinUtils, error) {
u, err := newUtils()
if err != nil {
return nil, err
}
return &IRacingWinUtils{u}, nil
}
func (u *IRacingWinUtils) Close() {
u.Utils.Close()
}
// OpenMemMap returns a Reader interface that can be used to read the data
// No need to encapsulate it
func OpenMemMap(path string, size uint32) (Reader, error) {
file, err := sharedMem.Open(path, size)
if err != nil {
return nil, err
}
return file, nil
}
// OpenWinEvent will open the named windows event
func (u *IRacingWinUtils) OpenWinEvent(name string) error {
return u.Utils.OpenEvent(name)
}
// OpenWinEvent will open the broadcast channel
func (u *IRacingWinUtils) OpenBroadcastChannel(name string) error {
return u.Utils.OpenBroadcastChannel(name)
}
// CheckValidDataEvent checks if our windows even is telling us we are good to go
func (u *IRacingWinUtils) CheckValidDataEvent(timeout time.Duration) bool {
return u.Utils.CheckValidDataEvent(timeout)
}
-53
View File
@@ -1,53 +0,0 @@
//go:build (linux && cgo) || (darwin && cgo)
// +build linux,cgo darwin,cgo
package winutils
import (
"errors"
"sync"
"time"
)
const (
WAIT_OBJECT_0 = 0
WAIT_TIMEOUT = 258
)
var (
once sync.Once
ErrUnsupportedOS = errors.New("not found")
)
type utils struct {
}
// INITIALIZATION
func newUtils() (*utils, error) {
return nil, ErrUnsupportedOS
}
func (u *utils) Close() {
}
// openEvent opens a windows.Handle for a given event
func (u *utils) OpenEvent(eventName string) error {
return ErrUnsupportedOS
}
// OpenBroadcastChannel opens up a broadcast channel to send commands to iracing
func (u *utils) OpenBroadcastChannel(name string) error {
return ErrUnsupportedOS
}
// INITIALIZATION
// openEvent waits for a good response for some given time
func (u *utils) CheckValidDataEvent(timeout time.Duration) bool {
return false
}
// SendBroadcastMessage sends a message trough the broadcast channel
func (u *utils) SendBroadcastMessage(id, p1, p2 uintptr) error {
return ErrUnsupportedOS
}