7 Commits
8 changed files with 407 additions and 51 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
- [ ] Change the pattern in which the data is fetched from the telemetry and
how it is exported into `.ibt` files
# About
This project will be able to parse `.ibt` files, read live data from races and
broadcast messages to the service. Its still not very mature at all, but after
this commit I will turn it into a package instead and give it a stable API.
Will also put some examples then.
This project is a simple Go SDK for the popular iRacing racing simulator.
It has the capabilites to:
- Read live data (live session or replay)
- 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
I used various sources to develop and understand how `iRacing` works, and learn
a lot with it. Once I have matured this project a bit I will document its
inner workings too.
## Usage
The SDK instance is created by calling `goirsdk.Init(Reader, exportTelem, exportYAML)`
- `Reader` is a variable that implements the interface:
```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
+66
View File
@@ -0,0 +1,66 @@
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
}
}
-5
View File
@@ -8,8 +8,3 @@ require (
golang.org/x/text v0.19.0
gopkg.in/yaml.v3 v3.0.1
)
require (
golang.org/x/lint v0.0.0-20241112194109-818c5a804067 // indirect
golang.org/x/tools v0.29.0 // indirect
)
-17
View File
@@ -1,26 +1,9 @@
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/lint v0.0.0-20241112194109-818c5a804067 h1:adDmSQyFTCiv19j015EGKJBoaa7ElV0Q1Wovb/4G7NA=
golang.org/x/lint v0.0.0-20241112194109-818c5a804067/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.29.0 h1:Xx0h3TtM9rzQpQuR4dKLrdglAmCEN5Oi+P74JdhdzXE=
golang.org/x/tools v0.29.0/go.mod h1:KMQVMRsVxU6nHCFXrBPhDB8XncLNLM0lIy/F14RP588=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
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/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+14 -9
View File
@@ -2,8 +2,6 @@
package goirsdk
import (
// "github.com/ESilva15/goirsdk/logger"
"fmt"
"os"
@@ -79,21 +77,27 @@ func (i *IBT) exportYAML() error {
}
func (i *IBT) exportIBT(data []byte, offset int64) error {
log := logger.GetInstance()
log := logger.GetInstance()
_, err := i.IBTExport.WriteAt(data, offset)
if err != nil {
i.IBTExport.Close()
i.IBTExport = nil
log.Println("Won't attempt to export anymore")
return err
}
if err != nil {
i.IBTExport.Close()
i.IBTExport = nil
log.Println("Won't attempt to export anymore")
return err
}
return nil
}
// Init serves to initialize and get a hold of a IBT struct
// f -> is the source data, pass nil for the SDK to read live data or a
// *os.File to read from a file
// exportTelem -> is a string with the path to export the telemetry data, pass
// an empty string to not export any data
// exportTelem -> is a string with the path to export the session info data, pass
// an empty string to not export any data
func Init(f Reader, exportTelem string, exportYAML string) (*IBT, error) {
// log := logger.GetInstance()
@@ -172,6 +176,7 @@ func Init(f Reader, exportTelem string, exportYAML string) (*IBT, error) {
return &ibt, nil
}
// Close cleans up our irsdk instance
func (i *IBT) Close() {
if i.winUtils != nil {
// If its not live data, the user is the one with ownership of the handle
+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
}
}
+6 -4
View File
@@ -321,9 +321,11 @@ func (i *IBT) readSessionInfo() error {
}
// Write to the output file
_, err = i.IBTExport.WriteAt(sessionInfoStringRaw[:], int64(i.Headers.SessionInfoOffset))
if err != nil {
return fmt.Errorf("Failed to export session info string: %v\n", err)
if i.IBTExport != nil {
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)
@@ -335,7 +337,7 @@ func (i *IBT) readSessionInfo() error {
if i.YAMLExportPath != "" {
err := i.exportYAML()
if err != nil {
log.Println("Failed to export YAML string: %v\n", err)
log.Printf("Failed to export YAML string: %v\n", err)
}
}
+111 -8
View File
@@ -71,6 +71,20 @@ type Var struct {
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 {
return fmt.Sprintf(
"Type: %5d (0x%08x)\n"+
@@ -147,17 +161,103 @@ func (i *IBT) readData(buf []byte) error {
// Read the value
switch v.Type {
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:
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:
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:
v.Value = fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
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 := fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
data[entry] = newValue
}
v.Value = data
} else {
// Single value
v.Value = fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
}
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:
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)))
}
}
// --------------
@@ -167,6 +267,8 @@ func (i *IBT) readData(buf []byte) error {
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) {
if i.winUtils != nil {
// Put a way to check if the sim is active here
@@ -222,6 +324,7 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
return Ended, nil
}
// Document why this is here, I don't remember the exact words right now
i.Vars.RecorderTick++
} else {
// This will get the dataframe corresponding to a given tick
@@ -231,12 +334,12 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
// Make this happen in a different thread, or have this send to a queue that has a thread
// writing to a file
if i.IBTExport != nil {
if i.IBTExport != nil {
err = i.exportIBT(buf, int64(start))
if err != nil {
log.Printf("Failed to export offline telemetry data: %v", err)
}
}
}
if err == io.EOF {
return Ended, nil