43 Commits
Author SHA1 Message Date
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
esilva 45a0aa43aa This was on the wrong place 2025-01-06 18:29:45 +00:00
esilva 38e7ea32cc Add the method for SessionInfo export 2025-01-06 18:01:56 +00:00
esilva bcbffdc7a2 Some miscellanious stuff 2025-01-06 17:52:12 +00:00
esilva 2dc1771bb6 Fixed the file exporting for live telemetry data 2025-01-06 17:46:14 +00:00
esilva f925cede6d Add the ability to export to an IBT file 2025-01-03 14:31:25 +00:00
esilva 300c86190b Updated this to use the package 2024-11-05 18:05:27 +00:00
esilva 5fa39f2935 Merge branch 'master' into unittesting 2024-11-05 18:02:59 +00:00
esilva 423b8dcc22 Move this into its own package 2024-11-05 17:54:41 +00:00
esilva b6aaaab8b2 Merge branch 'master' of ssh://esilva.org:666/home/esilva/privGit/ibtReader 2024-11-05 15:51:13 +00:00
esilva 0f33e19558 Added the README 2024-11-05 15:50:52 +00:00
esilva 57d006c0e7 Addig the PDF document I found with some data 2024-11-03 22:57:24 +00:00
esilva 23a7efc37d Moved the check for EOF on the Update method 2024-11-03 22:54:40 +00:00
esilva 7a1b128d6b Got the constants from the CPP SDK and will comb trough them later 2024-11-02 16:03:34 +00:00
esilva 2e1b811a80 Forgot to add the cmp pacakge 2024-11-02 16:02:33 +00:00
esilva 6d03e46b44 Added the test for the disksubheaders and fixed the headers one 2024-11-02 16:02:21 +00:00
esilva f8149d687d Merge branch 'master' into unittesting 2024-11-02 15:38:04 +00:00
esilva dcfaec6d63 Moved the mstokph function to a subpackage of its own (conversions) 2024-11-02 15:36:56 +00:00
esilva b66606fc6c Added the gitignore 2024-11-02 15:33:50 +00:00
esilva e153a2efb1 Added a telemetry file to use for testing stuff and whatnot 2024-11-02 15:33:25 +00:00
esilva b2a3e2f97c Added a unittest for the header parsing 2024-11-01 22:42:33 +00:00
esilva 4c795c49c4 Removed the check for the length of header size because its a fixed size buf 2024-11-01 22:38:15 +00:00
esilva 7ce4d0ed4b Added the Linux and Darwin stubs for the winutils package
This means that the livedata bit of the code is only available on
windows
2024-10-30 23:26:29 +00:00
esilva 422d90e98a The live data also works now, but I have some refactoring to do 2024-10-29 14:52:40 +00:00
esilva dbf30c1d4e Fixed the width, its only for the looks 2024-10-29 14:52:21 +00:00
esilva 78a2512410 Code now runs on Linux for local files
I still need to add the support for message broadcasting tho, it should
not be that hard
2024-10-28 12:15:16 +00:00
esilva d48a6fa24a SessionInfo parsing and another stuff 2024-10-27 23:25:28 +00:00
esilva 2bc756a2f0 Rolled back some stuff here like the package stuff
This will add support to view live data
2024-10-27 22:48:32 +00:00
29 changed files with 2791 additions and 765 deletions
+2
View File
@@ -0,0 +1,2 @@
coverage*
*.txt
+3
View File
@@ -0,0 +1,3 @@
test:
go test -coverprofile=coverage.out ./... -cover -bench=
go tool cover -html=coverage.out -o coverage.html
+118
View File
@@ -0,0 +1,118 @@
# 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
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.
## 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
I vendored in the code from [hidez8891/shm](https://github.com/hidez8891/shm)
since the repo has been archived. I took the opportunity to update some of its
code.
+274
View File
@@ -0,0 +1,274 @@
package goirsdk
type Msg struct {
Cmd int
P1 int32
P2 int32
P3 int32
}
const (
MEMMAPFILENAME = "IRSDKMemMapFileName"
SimStatusUrl string = "http://127.0.0.1:32034/get_sim_status?object=simStatus"
IRSDK_DATAVALIDEVENTNAME string = "Local\\IRSDKDataValidEvent"
IRSDK_MEMMAPFILENAME string = "Local\\" + MEMMAPFILENAME
IRSDK_BROADCASTMSGNAME string = "IRSDK_BROADCASTMSG"
fileMapSize uint32 = 1164 * 1024
connTimeout int64 = 30
stConnected int = 1
)
const (
BroadcastCamSwitchPos int = 0 // car position, group, camera
BroadcastCamSwitchNum int = 1 // driver #, group, camera
BroadcastCamSetState int = 2 // irsdk_CameraState, unused, unused
BroadcastReplaySetPlaySpeed int = 3 // speed, slowMotion, unused
BroadcastReplaySetPlayPosition int = 4 // irsdk_RpyPosMode, Frame Number (high, low)
BroadcastReplaySearch int = 5 // irsdk_RpySrchMode, unused, unused
BroadcastReplaySetState int = 6 // irsdk_RpyStateMode, unused, unused
BroadcastReloadTextures int = 7 // irsdk_ReloadTexturesMode, carIdx, unused
BroadcastChatComand int = 8 // irsdk_ChatCommandMode, subCommand, unused
BroadcastPitCommand int = 9 // irsdk_PitCommandMode, parameter
BroadcastTelemCommand int = 10 // irsdk_TelemCommandMode, unused, unused
BroadcastFFBCommand int = 11 // irsdk_FFBCommandMode, value (float, high, low)
BroadcastReplaySearchSessionTime int = 12 // sessionNum, sessionTimeMS (high, low)
BroadcastLast int = 13 // unused placeholder
)
const (
ChatCommandMacro int = 0 // pass in a number from 1-15 representing the chat macro to launch
ChatCommandBeginChat int = 1 // Open up a new chat window
ChatCommandReply int = 2 // Reply to last private chat
ChatCommandCancel int = 3 // Close chat window
)
// this only works when the driver is in the car
const (
PitCommandClear int = 0 // Clear all pit checkboxes
PitCommandWS int = 1 // Clean the winshield, using one tear off
PitCommandFuel int = 2 // Add fuel, optionally specify the amount to add in liters or pass '0' to use existing amount
PitCommandLF int = 3 // Change the left front tire, optionally specifying the pressure in KPa or pass '0' to use existing pressure
PitCommandRF int = 4 // right front
PitCommandLR int = 5 // left rear
PitCommandRR int = 6 // right rear
PitCommandClearTires int = 7 // Clear tire pit checkboxes
PitCommandFR int = 8 // Request a fast repair
PitCommandClearWS int = 9 // Uncheck Clean the winshield checkbox
PitCommandClearFR int = 10 // Uncheck request a fast repair
PitCommandClearFuel int = 11 // Uncheck add fuel
)
// You can call this any time, but telemtry only records when driver is in there car
const (
TelemCommandStop int = 0 // Turn telemetry recording off
TelemCommandStart int = 1 // Turn telemetry recording on
TelemCommandRestart int = 2 // Write current file to disk and start a new one
)
const (
RpyStateEraseTape int = 0 // clear any data in the replay tape
RpyStateLast int = 1 // unused place holder
)
const (
ReloadTexturesAll int = 0 // reload all textuers
ReloadTexturesCarIdx int = 1 // reload only textures for the specific carIdx
)
// Search replay tape for events
const (
RpySrchToStart int = 0
RpySrchToEnd int = 1
RpySrchPrevSession int = 2
RpySrchNextSession int = 3
RpySrchPrevLap int = 4
RpySrchNextLap int = 5
RpySrchPrevFrame int = 6
RpySrchNextFrame int = 7
RpySrchPrevIncident int = 8
RpySrchNextIncident int = 9
RpySrchLast int = 10 // unused placeholder
)
const (
RpyPosBegin int = 0
RpyPosCurrent int = 1
RpyPosEnd int = 2
RpyPosLast int = 3 // unused placeholder
)
// You can call this any time
const (
FFBCommandMaxForce int = 0 // Set the maximum force when mapping steering torque force to direct input units (float in Nm)
FFBCommandLast int = 1 // unused placeholder
)
// irsdk_BroadcastCamSwitchPos or irsdk_BroadcastCamSwitchNum camera focus defines
// pass these in for the first parameter to select the 'focus at' types in the camera system.
const (
csFocusAtIncident int = -3
csFocusAtLeader int = -2
csFocusAtExiting int = -1
csFocusAtDriver int = 0 // ctFocusAtDriver + car number...
)
// Camera positions
const (
// CamNose
)
// Some other constants that I need to get trough
// // bit fields
type bitfieldValue struct {
Value int
Name string
}
// EngineWarnings const
var (
irsdkWaterTempWarning = bitfieldValue{0x01, "irsdk_waterTempWarning"}
irsdkFuelPressureWarning = bitfieldValue{0x02, "irsdk_fueldPressureWarning"}
irsdkOilPressureWarning = bitfieldValue{0x04, "irsdk_oilPressureWarning"}
irsdkEngineStalled = bitfieldValue{0x08, "irsdk_engineStalled"}
irsdkPitSpeedLimiter = bitfieldValue{0x10, "irsdk_pitSpeedLimiter"}
irsdkRevLimiterActive = bitfieldValue{0x20, "irsdk_revLimiterActive"}
irsdkAbsActive = bitfieldValue{0x100, "irsdk_absActive"}
irsdkEngineWarnings = []bitfieldValue{
irsdkWaterTempWarning, irsdkFuelPressureWarning,
irsdkOilPressureWarning, irsdkEngineStalled, irsdkPitSpeedLimiter, irsdkRevLimiterActive,
irsdkAbsActive,
}
)
// enum irsdk_EngineWarnings
// {
// irsdk_waterTempWarning = 0x01,
// irsdk_fuelPressureWarning = 0x02,
// irsdk_oilPressureWarning = 0x04,
// irsdk_engineStalled = 0x08,
// irsdk_pitSpeedLimiter = 0x10,
// irsdk_revLimiterActive = 0x20,
// };
//
// // global flags
// enum irsdk_Flags
// {
// // global flags
// irsdk_checkered = 0x00000001,
// irsdk_white = 0x00000002,
// irsdk_green = 0x00000004,
// irsdk_yellow = 0x00000008,
// irsdk_red = 0x00000010,
// irsdk_blue = 0x00000020,
// irsdk_debris = 0x00000040,
// irsdk_crossed = 0x00000080,
// irsdk_yellowWaving = 0x00000100,
// irsdk_oneLapToGreen = 0x00000200,
// irsdk_greenHeld = 0x00000400,
// irsdk_tenToGo = 0x00000800,
// irsdk_fiveToGo = 0x00001000,
// irsdk_randomWaving = 0x00002000,
// irsdk_caution = 0x00004000,
// irsdk_cautionWaving = 0x00008000,
//
// // drivers black flags
// irsdk_black = 0x00010000,
// irsdk_disqualify = 0x00020000,
// irsdk_servicible = 0x00040000, // car is allowed service (not a flag)
// irsdk_furled = 0x00080000,
// irsdk_repair = 0x00100000,
//
// // start lights
// irsdk_startHidden = 0x10000000,
// irsdk_startReady = 0x20000000,
// irsdk_startSet = 0x40000000,
// irsdk_startGo = 0x80000000,
// };
//
//
// // status
// enum irsdk_TrkLoc
// {
// irsdk_NotInWorld = -1,
// irsdk_OffTrack,
// irsdk_InPitStall,
// irsdk_AproachingPits,
// irsdk_OnTrack
// };
//
// enum irsdk_TrkSurf
// {
// irsdk_SurfaceNotInWorld = -1,
// irsdk_UndefinedMaterial = 0,
//
// irsdk_Asphalt1Material,
// irsdk_Asphalt2Material,
// irsdk_Asphalt3Material,
// irsdk_Asphalt4Material,
// irsdk_Concrete1Material,
// irsdk_Concrete2Material,
// irsdk_RacingDirt1Material,
// irsdk_RacingDirt2Material,
// irsdk_Paint1Material,
// irsdk_Paint2Material,
// irsdk_Rumble1Material,
// irsdk_Rumble2Material,
// irsdk_Rumble3Material,
// irsdk_Rumble4Material,
//
// irsdk_Grass1Material,
// irsdk_Grass2Material,
// irsdk_Grass3Material,
// irsdk_Grass4Material,
// irsdk_Dirt1Material,
// irsdk_Dirt2Material,
// irsdk_Dirt3Material,
// irsdk_Dirt4Material,
// irsdk_SandMaterial,
// irsdk_Gravel1Material,
// irsdk_Gravel2Material,
// irsdk_GrasscreteMaterial,
// irsdk_AstroturfMaterial,
// };
//
// enum irsdk_SessionState
// {
// irsdk_StateInvalid,
// irsdk_StateGetInCar,
// irsdk_StateWarmup,
// irsdk_StateParadeLaps,
// irsdk_StateRacing,
// irsdk_StateCheckered,
// irsdk_StateCoolDown
// };
//
// enum irsdk_CameraState
// {
// irsdk_IsSessionScreen = 0x0001, // the camera tool can only be activated if viewing the session screen (out of car)
// irsdk_IsScenicActive = 0x0002, // the scenic camera is active (no focus car)
//
// //these can be changed with a broadcast message
// irsdk_CamToolActive = 0x0004,
// irsdk_UIHidden = 0x0008,
// irsdk_UseAutoShotSelection = 0x0010,
// irsdk_UseTemporaryEdits = 0x0020,
// irsdk_UseKeyAcceleration = 0x0040,
// irsdk_UseKey10xAcceleration = 0x0080,
// irsdk_UseMouseAimMode = 0x0100
// };
//
// enum irsdk_PitSvFlags
// {
// irsdk_LFTireChange = 0x0001,
// irsdk_RFTireChange = 0x0002,
// irsdk_LRTireChange = 0x0004,
// irsdk_RRTireChange = 0x0008,
//
// irsdk_FuelFill = 0x0010,
// irsdk_WindshieldTearoff = 0x0020,
// irsdk_FastRepair = 0x0040
// };
//----
//
+5
View File
@@ -0,0 +1,5 @@
package conversions
func MsToKph(v float32) int {
return int((3600 * v) / 1000)
}
+76 -47
View File
@@ -1,47 +1,76 @@
package ibtReader
import (
"bytes"
"encoding/binary"
"fmt"
)
const (
SubHeaderSize = 32 // SubHeaderSize is the size of the subheader
)
// DiskSubHeader represents the IBT sub headers
type DiskSubHeader struct {
StartDate int64 // StartDate represents the start date of the telemetry
StartTime float64 // StartTime of file relative to start of session
EndTime float64 // EndTime of file relative to start of session
LapCount int32 // LapCount represents the total number laps
RecordCount int32 // RecordCount holds the number of data frames
}
// parseTelemetrySubHeader will return a pointer to a DiskSubHeader variable
// or nil if an error occurs. In which case the error return value is more
// valuable
func parseTelemetrySubHeader(buf [SubHeaderSize]byte) (*DiskSubHeader, error) {
dst := DiskSubHeader{}
err := binary.Read(bytes.NewBuffer(buf[:]), binary.LittleEndian, &dst)
if err != nil {
return nil, err
}
return &dst, nil
}
// ToString renders a string showing the values of the struct
func (d *DiskSubHeader) ToString() string {
return fmt.Sprintf(
"StartDate: %13d (0x%04x)\n"+
"StartTime: %13f (0x%08x)\n"+
"EndTime: %13f (0x%08x)\n"+
"LapCount: %13d (0x%04x)\n"+
"RecordCount: %13d (0x%04x)\n",
d.StartDate, d.StartDate, d.StartTime, d.StartTime,
d.EndTime, d.EndTime, d.LapCount, d.LapCount,
d.RecordCount, d.RecordCount,
)
}
package goirsdk
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/ESilva15/goirsdk/logger"
)
const (
SubHeaderSize = 32 // SubHeaderSize is the size of the subheader
)
// DiskSubHeader represents the IBT sub headers
type DiskSubHeader struct {
StartDate int64 // StartDate represents the start date of the telemetry
StartTime float64 // StartTime of file relative to start of session
EndTime float64 // EndTime of file relative to start of session
LapCount int32 // LapCount represents the total number laps
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 {
log := logger.GetInstance()
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 {
log.Printf("failed to export subheaders: %v\n", err)
}
}
return nil
}
// parseTelemetrySubHeader will return a pointer to a DiskSubHeader variable
// or nil if an error occurs. In which case the error return value is more
// valuable
func parseTelemetrySubHeader(buf [SubHeaderSize]byte) (*DiskSubHeader, error) {
// utils.HexDump(buf[:])
dst := DiskSubHeader{}
err := binary.Read(bytes.NewBuffer(buf[:]), binary.LittleEndian, &dst)
if err != nil {
return nil, err
}
return &dst, nil
}
// ToString renders a string showing the values of the struct
func (d *DiskSubHeader) ToString() string {
return fmt.Sprintf(
"StartDate: %13d (0x%04x)\n"+
"StartTime: %13f (0x%08x)\n"+
"EndTime: %13f (0x%08x)\n"+
"LapCount: %13d (0x%04x)\n"+
"RecordCount: %13d (0x%04x)\n",
d.StartDate, d.StartDate, d.StartTime, d.StartTime,
d.EndTime, d.EndTime, d.LapCount, d.LapCount,
d.RecordCount, d.RecordCount,
)
}
+38
View File
@@ -0,0 +1,38 @@
package goirsdk
import (
"testing"
"github.com/google/go-cmp/cmp"
)
// TestParseTelemetrySubHeader_WithGoodBuffer
// Given a well structured buffer it will output the expected
// DiskSubHeader struct
func TestParseTelemetrySubHeader_WithGoodBuffer(t *testing.T) {
// Arrange
header := [32]byte{
0x54, 0x1e, 0x14, 0x67, 0x00, 0x00, 0x00, 0x00, 0x54, 0x09, 0x00, 0xf0,
0xee, 0x7e, 0x6b, 0x40, 0x53, 0x74, 0x88, 0x44, 0x44, 0x86, 0x8f, 0x40,
0x08, 0x00, 0x00, 0x00, 0xe1, 0xb8, 0x00, 0x00,
}
expectedHeader := DiskSubHeader{
StartDate: 1729371732,
StartTime: 219.96666717536084,
EndTime: 1008.7833338413715,
LapCount: 8,
RecordCount: 47329,
}
// Act
headers, err := parseTelemetrySubHeader(header)
// Assert
if err != nil {
t.Fatalf("Error parsing buffer: %v", err)
}
if !cmp.Equal(&expectedHeader, headers) {
t.Fatalf("Expected:\n%#v\nGot:\n%#v\n", expectedHeader, headers)
}
}
@@ -0,0 +1,66 @@
package main
import (
"fmt"
"log"
"time"
"github.com/ESilva15/goirsdk"
)
func msToKph(v float32) int {
return int((3600 * v) / 1000)
}
func main() {
// Instantiate our iRacing SDK instance
irsdk, err := goirsdk.Init(goirsdk.Options{
SourceType: goirsdk.IBTFile,
SourcePath: "../../../../testTelemetry/gt3_mustang_bathurst.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)))
fmt.Printf("\033[?25l\033[2J\033[H")
fmt.Printf("Gear: %d, RPM: %d, Speed: %d", gear, rpm, speed)
<-mainLoopTicker.C
}
}
@@ -0,0 +1,62 @@
package main
import (
"fmt"
"log"
"time"
"github.com/ESilva15/goirsdk"
)
func msToKph(v float32) int {
return int((3600 * v) / 1000)
}
func main() {
// Instantiate our iRacing SDK instance
irsdk, err := goirsdk.Init(goirsdk.Options{
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)))
fmt.Printf("\033[?25l\033[2J\033[H")
fmt.Printf("Gear: %d, RPM: %d, Speed: %d", gear, rpm, speed)
<-mainLoopTicker.C
}
}
+7 -2
View File
@@ -1,5 +1,10 @@
module esilvalabs.org/ibtReader.git
module github.com/ESilva15/goirsdk
go 1.23.2
require gopkg.in/yaml.v3 v3.0.1
require (
github.com/google/go-cmp v0.6.0
golang.org/x/sys v0.29.0
golang.org/x/text v0.19.0
gopkg.in/yaml.v3 v3.0.1
)
+6
View File
@@ -1,3 +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/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+95 -80
View File
@@ -1,80 +1,95 @@
package ibtReader
import (
"bytes"
"encoding/binary"
"fmt"
)
const (
FileHeaderSize = 112 // FileHeaderSize is the size of the headers
HeaderSize = 4 // HeaderSize is the size of a single header
)
// TelemetryHeaders struct to hold an IBT file's headers
type TelemetryHeaders struct {
Version int32
// Status of 1 indicates a completed session and status of 0 a live session
Status int32
// TickRate indicates the frequency of writes (usually 60)
TickRate int32
// SessionInfoUpdate indicates the number of times the SessionInfo was
// updated. 0 for finished sessions and >1 for active sessions
SessionInfoUpdate int32
// SessionInfoLength is the length of the session info buffer
SessionInfoLength int32
// SessionInfoOffset is the offset of the session info in the buffer
SessionInfoOffset int32
// NumVars is the number of variables in each input
NumVars int32
// VarHeaderOffset is the offset of the VarHeader
VarHeaderOffset int32
// NumBuf will be 1 for static files and 3 for live telemetry files
NumBuf int32
// BufLen is the length for parsing VarHeader values
BufLen int32
// Padding
Padding [12]byte
// I still don't know what this is:
BufOffset int32
}
// ToString renders a string showing the values of the struct
func (th *TelemetryHeaders) ToString() string {
return fmt.Sprintf(
"Version: %5d (0x%04x)\n"+
"Status: %5d (0x%04x)\n"+
"TickRate: %5d (0x%04x)\n"+
"SIUpdate: %5d (0x%04x)\n"+
"SILength: %5d (0x%04x)\n"+
"SIOffset: %5d (0x%04x)\n"+
"NumVars: %5d (0x%04x)\n"+
"VarHeaderOffset: %5d (0x%04x)\n"+
"NumBuf: %5d (0x%04x)\n"+
"BufLen: %5d (0x%04x)\n"+
"BufOffset: %5d (0x%04x)\n",
th.Version, th.Version, th.Status, th.Status, th.TickRate, th.TickRate,
th.SessionInfoUpdate, th.SessionInfoUpdate,
th.SessionInfoLength, th.SessionInfoLength,
th.SessionInfoOffset, th.SessionInfoOffset,
th.NumVars, th.NumVars, th.VarHeaderOffset, th.VarHeaderOffset,
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) {
if len(buf)%HeaderSize != 0 {
return nil, fmt.Errorf("buffer must be multiple of size: %d", HeaderSize)
}
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
}
package goirsdk
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/ESilva15/goirsdk/logger"
)
const (
FileHeaderSize = 112 // FileHeaderSize is the size of the headers
HeaderSize = 4 // HeaderSize is the size of a single header
)
// TelemetryHeaders struct to hold an IBT file's headers
type TelemetryHeaders struct {
Version int32
Status int32 // Status of 1 indicates a completed session and status of 0 a live session
TickRate int32 // TickRate indicates the frequency of writes (usually 60)
SessionInfoUpdate int32 // SessionInfoUpdate indicates the number of times the SessionInfo was
// updated. 0 for finished sessions and >1 for active sessions
SessionInfoLength int32 // SessionInfoLength is the length of the session info buffer
SessionInfoOffset int32 // SessionInfoOffset is the offset of the session info in the buffer
NumVars int32 // NumVars is the number of variables in each input
VarHeaderOffset int32 // VarHeaderOffset is the offset of the VarHeader
NumBuf int32 // NumBuf will be 1 for static files and 3 for live telemetry files
BufLen int32 // BufLen is the length for parsing VarHeader values
Padding [12]byte // Padding
BufOffset int32 // I still don't know what this is:
}
// readHeader will read the header out of the telemetry data
func (i *IBT) readHeader() error {
log := logger.GetInstance()
var headerRaw [FileHeaderSize]byte
_, err := i.File.ReadAt(headerRaw[:], 0)
if err != nil {
return fmt.Errorf("failed to read headers from file: %v", err)
}
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 {
log.Printf("Failed to export headers: %v\n", 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
func (th *TelemetryHeaders) ToString() string {
return fmt.Sprintf(
"Version: %5d (0x%04x)\n"+
"Status: %5d (0x%04x)\n"+
"TickRate: %5d (0x%04x)\n"+
"SIUpdate: %5d (0x%04x)\n"+
"SILength: %5d (0x%04x)\n"+
"SIOffset: %5d (0x%04x)\n"+
"NumVars: %5d (0x%04x)\n"+
"VarHeaderOffset: %5d (0x%04x)\n"+
"NumBuf: %5d (0x%04x)\n"+
"BufLen: %5d (0x%04x)\n"+
"BufOffset: %5d (0x%04x)\n",
th.Version, th.Version, th.Status, th.Status, th.TickRate, th.TickRate,
th.SessionInfoUpdate, th.SessionInfoUpdate,
th.SessionInfoLength, th.SessionInfoLength,
th.SessionInfoOffset, th.SessionInfoOffset,
th.NumVars, th.NumVars, th.VarHeaderOffset, th.VarHeaderOffset,
th.NumBuf, th.NumBuf, th.BufLen, th.BufLen, th.BufOffset, th.BufOffset,
)
}
+52
View File
@@ -0,0 +1,52 @@
package goirsdk
import (
"testing"
"github.com/google/go-cmp/cmp"
)
// TestParseTelemetryHeader_WithGoodBuffer
// Given a well structured buffer it will output the expected
// TelemetryHeaders struct
func TestParseTelemetryHeader_WithGoodBuffer(t *testing.T) {
// Arrange
header := [112]byte{
0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x3f, 0x00, 0x00, 0x90, 0x99, 0x00, 0x00,
0x10, 0x01, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x1d, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x60, 0x2b, 0x00, 0x00, 0x95, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
}
expectedHeader := TelemetryHeaders{
Version: 2,
Status: 1,
TickRate: 60,
SessionInfoUpdate: 0,
SessionInfoLength: 16133,
SessionInfoOffset: 39312,
NumVars: 272,
VarHeaderOffset: 144,
NumBuf: 1,
BufLen: 1053,
Padding: [12]byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x60, 0x2b, 0x0, 0x0},
BufOffset: 55445,
}
// Act
headers, err := parseTelemetryHeader(header)
// Assert
if err != nil {
t.Fatalf("Error parsing buffer: %v", err)
}
if !cmp.Equal(&expectedHeader, headers) {
t.Fatalf("Expected:\n%#v\nGot:\n%#v\n", expectedHeader, headers)
}
}
+242 -136
View File
@@ -1,136 +1,242 @@
// Package IbtReader is all you need for you iRacing telemetry parsing
package ibtReader
import (
"fmt"
"io"
)
const (
ibtFile = "./telemetryFiles/mx5_2016Okayama_full_2024_10_19_22_02_12.ibt"
)
// Reader is an interface to represent the readable data that can be either
// a .ibt file (or live data, hopefully)
type Reader interface {
io.Reader
io.ReaderAt
io.ReadCloser
}
// IBT struct will hold the relevant data for a given IBT file
type IBT struct {
File Reader // Source of the data
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
Tick int32 // Tick holds the cound of the reads
}
// Init serves to initialize and get a hold of a IBT struct
func Init(f Reader) (*IBT, error) {
// Read the header of the file
var err error
ibt := IBT{
File: f,
Vars: &TelemetryVars{},
}
// Read the file headers
var headerRaw [FileHeaderSize]byte
_, err = ibt.File.ReadAt(headerRaw[:], 0)
if err != nil {
return nil, fmt.Errorf("Failed to read headers from file: %v", err)
}
ibt.Headers, err = parseTelemetryHeader(headerRaw)
if err != nil {
return nil, fmt.Errorf("Unable to read headers from file: %v", err)
}
// Read the disk sub headers
var subheaderRaw [SubHeaderSize]byte
_, err = ibt.File.ReadAt(subheaderRaw[:], 112)
if err != nil {
return nil, fmt.Errorf("Failed to read disk subheaders from file: %v", err)
}
ibt.SubHeaders, err = parseTelemetrySubHeader(subheaderRaw)
if err != nil {
return nil, fmt.Errorf("Unable to parse disk subheaders from file: %v", err)
}
// Read session info string
sessionInfoStringRaw := make([]byte, ibt.Headers.SessionInfoLength)
_, err = ibt.File.ReadAt(sessionInfoStringRaw, int64(ibt.Headers.SessionInfoOffset))
if err != nil {
return nil, fmt.Errorf("Failed to read sessionInfoString from file: %v", err)
}
ibt.SessionInfo, err = parseSessionInfo(sessionInfoStringRaw)
if err != nil {
return nil, fmt.Errorf("Unable to parse SessionInfoString from file: %v", err)
}
// Read the telemetry vars info
err = ibt.readVariablerHeaders()
if err != nil {
return nil, fmt.Errorf("Unable to parser variable headers from file: %v", err)
}
return &ibt, nil
}
func msToKph(v float32) int {
return int((3600 * v) / 1000)
}
// func main() {
// fmt.Println("================== IBT FILE PARSER ==================")
//
// file, err := os.Open(ibtFile)
// if err != nil {
// log.Fatalf("Failed to open IBT file: %v", err)
// }
//
// ibt, err := Init(file)
// fmt.Printf("%s\n", ibt.Headers.ToString())
// fmt.Printf("%s\n", ibt.SubHeaders.ToString())
//
// // Display the human readable start date
// unixStartDate := time.Unix(ibt.SubHeaders.StartDate, 0)
// startDate := unixStartDate.Format("2006/01/02 15:04:05 -0700 MST")
// fmt.Println("StartDate:", startDate)
//
// // Display the human readable version of start time
// unixStartTime := time.Unix(ibt.SubHeaders.StartDate+int64(ibt.SubHeaders.StartTime), 0)
// startTime := unixStartTime.Format("2006/01/02 15:04:05 -0700 MST")
// fmt.Println("StartTime:", startTime)
//
// // Display the human readable version of end time
// unixEndTime := time.Unix(ibt.SubHeaders.StartDate+int64(ibt.SubHeaders.EndTime), 0)
// endTime := unixEndTime.Format("2006/01/02 15:04:05 -0700 MST")
// fmt.Println("EndTime: ", endTime)
//
// last := time.Now().UnixMilli()
// for {
// time.Sleep(time.Second / 60)
// res := ibt.Update()
//
// curTime := time.Now().UnixMilli()
//
// if curTime-last > 250 {
// fmt.Printf(" \r")
// if val, ok := ibt.Vars.Vars["Speed"]; ok {
// fmt.Printf("\r%d %d", ibt.Tick/60, msToKph(val.Value.(float32)))
// } else {
// fmt.Printf("\r%d %s", ibt.Tick/60, "KEY DOESN'T EXIST")
// }
// }
//
// if !res {
// fmt.Println("\nEnd of file found...")
// break
// }
// }
//
// fmt.Printf("%d\n", ibt.Tick)
// }
// Package goirsdk is all you need for you iRacing telemetry parsing
package goirsdk
import (
"fmt"
"io"
"os"
"github.com/ESilva15/goirsdk/logger"
"github.com/ESilva15/goirsdk/mmaputils"
"github.com/ESilva15/goirsdk/sharedMem"
"gopkg.in/yaml.v3"
)
// Reader is an interface to represent the readable data that can be either
// a .ibt file (or live data, hopefully)
type Reader interface {
io.Reader
io.ReaderAt
io.ReadCloser
}
type Writer interface {
io.WriterAt
io.Closer
}
type TelemetryContainer int
const (
IBTFile TelemetryContainer = iota
SharedMemoryFile TelemetryContainer = iota
)
type Options struct {
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
type IBT struct {
File Reader // Source of the data
Opts Options
// TODO: IBTExporter should be an interface because we need to support shm too
IBTExporter Writer
// IBTExport *os.File // If set, it will export the IBT data to the file
// IBTExportPath string // Path for IBT export
// YAMLExport *os.File // If set, it will export the session YAML to the file
// YAMLExportPath string // Path for YAML export
winUtils *mmaputils.IRacingWinUtils // WinUtils gives access to the system utilities
// TODO: fragment this struct a little bit, for now I want to actually get
// stuff done so its enough to work as is
// 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 {
if i.Headers != nil {
if sessionStatusOK(int(i.Headers.Status)) {
return true
}
// if sessionStatusOK(int(i.Headers.Status)) && (sdk.lastValidData+connTimeout > time.Now().Unix()) {
// return true
// }
}
return false
}
func (i *IBT) exportYAML() error {
log := logger.GetInstance()
file, err := os.OpenFile(i.Opts.SessionInfoExportPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
log.Printf("Failed to open file for YAML export: %v\n", err)
return fmt.Errorf("failed to open output file for YAML: %v", err)
}
defer file.Close()
enc := yaml.NewEncoder(file)
err = enc.Encode(i.SessionInfo)
if err != nil {
log.Printf("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
}
func (i *IBT) exportIBT(data []byte, offset int64) error {
log := logger.GetInstance()
_, err := i.IBTExporter.WriteAt(data, offset)
if err != nil {
i.IBTExporter.Close()
i.IBTExporter = nil
log.Println("Won't attempt to export anymore")
return err
}
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
i.File, err = mmaputils.OpenMemMap(MEMMAPFILENAME, fileMapSize)
if err != nil {
return fmt.Errorf("failed to open memory mapped file: %+v", err)
}
// To use our windows interface we need to initialize it first
// 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
i.winUtils, err = mmaputils.Init()
if err != nil {
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
// err = i.winUtils.OpenWinEvent(IRSDK_DATAVALIDEVENTNAME)
// if err != nil {
// return err
// }
// We need to open the broadcast channel
// err = i.winUtils.OpenBroadcastChannel(IRSDK_BROADCASTMSGNAME)
// if err != nil {
// return err
// }
case IBTFile:
i.File, err = os.Open(i.Opts.SourcePath)
if err != nil {
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) {
// log := logger.GetInstance()
// Create our irsdk instance
var err error
ibt := IBT{
Opts: opts,
Vars: &TelemetryVars{},
winUtils: nil,
}
// 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
err = ibt.readHeader()
if err != nil {
return nil, err
}
// Read the disk sub headers
err = ibt.readSubheader()
if err != nil {
return nil, err
}
// Read session info string
err = ibt.readSessionInfo()
if err != nil {
return nil, err
}
// Read the telemetry vars info
err = ibt.readVariablerHeaders()
if err != nil {
return nil, fmt.Errorf("Unable to parser variable headers from file: %v", err)
}
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
i.File.Close()
i.winUtils.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
}
}
+23
View File
@@ -0,0 +1,23 @@
package logger
import (
"log"
"os"
"sync"
)
var l *log.Logger
var once sync.Once
func createLogger() {
l = log.New(os.Stdout, "[ibtReader] ", log.LstdFlags | log.Lshortfile)
}
func GetInstance() *log.Logger {
once.Do(func() {
createLogger()
})
return l
}
+47
View File
@@ -0,0 +1,47 @@
// 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 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()
}
// OpenWinEvent will open the named windows event
func (u *IRacingWinUtils) OpenWinEvent(name string) error {
return u.Utils.OpenEvent(name)
}
// OpenBroadcastChannel 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)
}
+129
View File
@@ -0,0 +1,129 @@
//go:build (linux && cgo) || (darwin && cgo)
package mmaputils
import (
"fmt"
"net"
"os"
"time"
"github.com/ESilva15/goirsdk/sharedMem"
)
type utils struct {
socketPath string
listener *net.UnixConn
}
func newUtils() (*utils, error) {
return &utils{}, nil
}
func (u *utils) Close() {
if u.listener != nil {
u.listener.Close()
os.Remove(u.socketPath)
}
}
// 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.socketPath = fmt.Sprintf("/tmp/iracing_%s.sock", eventName)
_ = os.Remove(u.socketPath)
addr, err := net.ResolveUnixAddr("unixgram", u.socketPath)
if err != nil {
return err
}
l, err := net.ListenUnixgram("unixgram", addr)
if err != nil {
return err
}
u.listener = l
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.listener == nil {
return false
}
_ = u.listener.SetReadDeadline(time.Now().Add(timeout))
buf := make([]byte, 1)
_, err := u.listener.Read(buf)
return err == nil
}
func (u *utils) SendBroadcastMessage(id, p1, p2 uintptr) error {
return nil
}
// 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
// }
+131
View File
@@ -0,0 +1,131 @@
// go:build windows
package mmaputils
import (
"sync"
"time"
"unsafe"
"github.com/ESilva15/goirsdk/sharedMem"
"golang.org/x/sys/windows"
)
const (
WAIT_OBJECT_0 = 0
WAIT_TIMEOUT = 258
)
var once sync.Once
type utils struct {
user32DLL *windows.LazyDLL
wEvent windows.Handle
wBroadcastChn uintptr
}
// INITIALIZATION
func newUtils() (*utils, error) {
return &utils{
user32DLL: openUser32DLL(),
}, nil
}
func (u *utils) Close() {
closeEvent(&u.wEvent)
// Do we need to unload the user32DLL ???
// 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
func (u *utils) OpenEvent(eventName string) error {
name, err := windows.UTF16PtrFromString(eventName)
if err != nil {
return err
}
event, err := windows.OpenEvent(windows.SYNCHRONIZE, false, name)
if err != nil {
return err
}
u.wEvent = event
return nil
}
// loadUser32DLL loads the user32.dll which is used to create some processes
func openUser32DLL() *windows.LazyDLL {
return windows.NewLazyDLL("user32.dll")
}
// OpenBroadcastChannel opens up a broadcast channel to send commands to iracing
func (u *utils) OpenBroadcastChannel(name string) error {
registerWindowsMessageW := u.user32DLL.NewProc("RegisterWindowMessageW")
msgPtr, err := windows.UTF16PtrFromString(name)
if err != nil {
return err
}
ret, _, err := registerWindowsMessageW.Call(uintptr(unsafe.Pointer(msgPtr)))
if ret == 0 {
return err
}
u.wBroadcastChn = ret
return nil
}
// INITIALIZATION
// closeEvent closes a given windows.Handle
func closeEvent(h *windows.Handle) {
windows.CloseHandle(*h)
}
// openEvent waits for a good response for some given time
func (u *utils) CheckValidDataEvent(timeout time.Duration) bool {
t0 := time.Now().UnixNano()
timeoutInt := uint32(timeout / time.Millisecond)
result, err := windows.WaitForSingleObject(u.wEvent, timeoutInt)
if err != nil {
remaining := timeoutInt - uint32((time.Now().UnixNano()-t0)/1000000)
if remaining > 0 {
time.Sleep(time.Duration(remaining) * time.Millisecond)
}
return false
}
// Check the result of the wait
if result == WAIT_OBJECT_0 {
return true
} else if result == WAIT_TIMEOUT {
return false
}
return false
}
// SendBroadcastMessage sends a message trough the broadcast channel
func (u *utils) SendBroadcastMessage(id, p1, p2 uintptr) error {
sendMsg := u.user32DLL.NewProc("SendNotifyMessageW")
ret, _, err := sendMsg.Call(0xffff, id, p1, p2)
if ret == 1 {
return nil
} else {
return err
}
}
+382 -323
View File
@@ -1,323 +1,382 @@
package ibtReader
import (
"encoding/json"
"gopkg.in/yaml.v3"
)
// SessionInfoYAML is a string with session info in the IBT file
type SessionInfoYAML struct {
WeekendInfo struct {
TrackName string `yaml:"TrackName"`
TrackID int `yaml:"TrackID"`
TrackLength string `yaml:"TrackLength"`
TrackDisplayName string `yaml:"TrackDisplayName"`
TrackDisplayShortName string `yaml:"TrackDisplayShortName"`
TrackConfigName string `yaml:"TrackConfigName"`
TrackCity string `yaml:"TrackCity"`
TrackCountry string `yaml:"TrackCountry"`
TrackAltitude string `yaml:"TrackAltitude"`
TrackLatitude string `yaml:"TrackLatitude"`
TrackLongitude string `yaml:"TrackLongitude"`
TrackNorthOffset string `yaml:"TrackNorthOffset"`
TrackNumTurns int `yaml:"TrackNumTurns"`
TrackPitSpeedLimit string `yaml:"TrackPitSpeedLimit"`
TrackType string `yaml:"TrackType"`
TrackDirection string `yaml:"TrackDirection"`
TrackWeatherType string `yaml:"TrackWeatherType"`
TrackSkies string `yaml:"TrackSkies"`
TrackSurfaceTemp string `yaml:"TrackSurfaceTemp"`
TrackAirTemp string `yaml:"TrackAirTemp"`
TrackAirPressure string `yaml:"TrackAirPressure"`
TrackWindVel string `yaml:"TrackWindVel"`
TrackWindDir string `yaml:"TrackWindDir"`
TrackRelativeHumidity string `yaml:"TrackRelativeHumidity"`
TrackFogLevel string `yaml:"TrackFogLevel"`
TrackCleanup int `yaml:"TrackCleanup"`
TrackDynamicTrack int `yaml:"TrackDynamicTrack"`
TrackVersion string `yaml:"TrackVersion"`
SeriesID int `yaml:"SeriesID"`
SeasonID int `yaml:"SeasonID"`
SessionID int `yaml:"SessionID"`
SubSessionID int `yaml:"SubSessionID"`
LeagueID int `yaml:"LeagueID"`
Official int `yaml:"Official"`
RaceWeek int `yaml:"RaceWeek"`
EventType string `yaml:"EventType"`
Category string `yaml:"Category"`
SimMode string `yaml:"SimMode"`
TeamRacing int `yaml:"TeamRacing"`
MinDrivers int `yaml:"MinDrivers"`
MaxDrivers int `yaml:"MaxDrivers"`
DCRuleSet string `yaml:"DCRuleSet"`
QualifierMustStartRace int `yaml:"QualifierMustStartRace"`
NumCarClasses int `yaml:"NumCarClasses"`
NumCarTypes int `yaml:"NumCarTypes"`
HeatRacing int `yaml:"HeatRacing"`
BuildType string `yaml:"BuildType"`
BuildTarget string `yaml:"BuildTarget"`
BuildVersion string `yaml:"BuildVersion"`
WeekendOptions struct {
NumStarters int `yaml:"NumStarters"`
StartingGrid string `yaml:"StartingGrid"`
QualifyScoring string `yaml:"QualifyScoring"`
CourseCautions string `yaml:"CourseCautions"`
StandingStart int `yaml:"StandingStart"`
ShortParadeLap int `yaml:"ShortParadeLap"`
Restarts string `yaml:"Restarts"`
WeatherType string `yaml:"WeatherType"`
Skies string `yaml:"Skies"`
WindDirection string `yaml:"WindDirection"`
WindSpeed string `yaml:"WindSpeed"`
WeatherTemp string `yaml:"WeatherTemp"`
RelativeHumidity string `yaml:"RelativeHumidity"`
FogLevel string `yaml:"FogLevel"`
TimeOfDay string `yaml:"TimeOfDay"`
Date string `yaml:"Date"`
EarthRotationSpeedupFactor int `yaml:"EarthRotationSpeedupFactor"`
Unofficial int `yaml:"Unofficial"`
CommercialMode string `yaml:"CommercialMode"`
NightMode string `yaml:"NightMode"`
IsFixedSetup int `yaml:"IsFixedSetup"`
StrictLapsChecking string `yaml:"StrictLapsChecking"`
HasOpenRegistration int `yaml:"HasOpenRegistration"`
HardcoreLevel int `yaml:"HardcoreLevel"`
NumJokerLaps int `yaml:"NumJokerLaps"`
IncidentLimit string `yaml:"IncidentLimit"`
FastRepairsLimit string `yaml:"FastRepairsLimit"`
GreenWhiteCheckeredLimit int `yaml:"GreenWhiteCheckeredLimit"`
} `yaml:"WeekendOptions"`
TelemetryOptions struct {
TelemetryDiskFile string `yaml:"TelemetryDiskFile"`
} `yaml:"TelemetryOptions"`
} `yaml:"WeekendInfo"`
SessionInfo struct {
Sessions []struct {
SessionNum int `yaml:"SessionNum"`
SessionLaps string `yaml:"SessionLaps"`
SessionTime string `yaml:"SessionTime"`
SessionNumLapsToAvg int `yaml:"SessionNumLapsToAvg"`
SessionType string `yaml:"SessionType"`
SessionTrackRubberState string `yaml:"SessionTrackRubberState"`
SessionName string `yaml:"SessionName"`
SessionSubType interface{} `yaml:"SessionSubType"`
SessionSkipped int `yaml:"SessionSkipped"`
SessionRunGroupsUsed int `yaml:"SessionRunGroupsUsed"`
ResultsPositions interface{} `yaml:"ResultsPositions"`
ResultsFastestLap []struct {
CarIdx int `yaml:"CarIdx"`
FastestLap int `yaml:"FastestLap"`
FastestTime int `yaml:"FastestTime"`
} `yaml:"ResultsFastestLap"`
ResultsAverageLapTime int `yaml:"ResultsAverageLapTime"`
ResultsNumCautionFlags int `yaml:"ResultsNumCautionFlags"`
ResultsNumCautionLaps int `yaml:"ResultsNumCautionLaps"`
ResultsNumLeadChanges int `yaml:"ResultsNumLeadChanges"`
ResultsLapsComplete int `yaml:"ResultsLapsComplete"`
ResultsOfficial int `yaml:"ResultsOfficial"`
} `yaml:"Sessions"`
} `yaml:"SessionInfo"`
CameraInfo struct {
Groups []struct {
GroupNum int `yaml:"GroupNum"`
GroupName string `yaml:"GroupName"`
Cameras []struct {
CameraNum int `yaml:"CameraNum"`
CameraName string `yaml:"CameraName"`
} `yaml:"Cameras"`
IsScenic bool `yaml:"IsScenic,omitempty"`
} `yaml:"Groups"`
} `yaml:"CameraInfo"`
RadioInfo struct {
SelectedRadioNum int `yaml:"SelectedRadioNum"`
Radios []struct {
RadioNum int `yaml:"RadioNum"`
HopCount int `yaml:"HopCount"`
NumFrequencies int `yaml:"NumFrequencies"`
TunedToFrequencyNum int `yaml:"TunedToFrequencyNum"`
ScanningIsOn int `yaml:"ScanningIsOn"`
Frequencies []struct {
FrequencyNum int `yaml:"FrequencyNum"`
FrequencyName string `yaml:"FrequencyName"`
Priority int `yaml:"Priority"`
CarIdx int `yaml:"CarIdx"`
EntryIdx int `yaml:"EntryIdx"`
ClubID int `yaml:"ClubID"`
CanScan int `yaml:"CanScan"`
CanSquawk int `yaml:"CanSquawk"`
Muted int `yaml:"Muted"`
IsMutable int `yaml:"IsMutable"`
IsDeletable int `yaml:"IsDeletable"`
} `yaml:"Frequencies"`
} `yaml:"Radios"`
} `yaml:"RadioInfo"`
DriverInfo struct {
DriverCarIdx int `yaml:"DriverCarIdx"`
DriverUserID int `yaml:"DriverUserID"`
PaceCarIdx int `yaml:"PaceCarIdx"`
DriverHeadPosX float64 `yaml:"DriverHeadPosX"`
DriverHeadPosY float64 `yaml:"DriverHeadPosY"`
DriverHeadPosZ float64 `yaml:"DriverHeadPosZ"`
DriverCarIdleRPM float64 `yaml:"DriverCarIdleRPM"`
DriverCarRedLine float64 `yaml:"DriverCarRedLine"`
DriverCarEngCylinderCount int `yaml:"DriverCarEngCylinderCount"`
DriverCarFuelKgPerLtr float64 `yaml:"DriverCarFuelKgPerLtr"`
DriverCarFuelMaxLtr float64 `yaml:"DriverCarFuelMaxLtr"`
DriverCarMaxFuelPct float64 `yaml:"DriverCarMaxFuelPct"`
DriverCarGearNumForward int `yaml:"DriverCarGearNumForward"`
DriverCarGearNeutral int `yaml:"DriverCarGearNeutral"`
DriverCarGearReverse int `yaml:"DriverCarGearReverse"`
DriverCarSLFirstRPM float64 `yaml:"DriverCarSLFirstRPM"`
DriverCarSLShiftRPM float64 `yaml:"DriverCarSLShiftRPM"`
DriverCarSLLastRPM float64 `yaml:"DriverCarSLLastRPM"`
DriverCarSLBlinkRPM float64 `yaml:"DriverCarSLBlinkRPM"`
DriverCarVersion string `yaml:"DriverCarVersion"`
DriverPitTrkPct float64 `yaml:"DriverPitTrkPct"`
DriverCarEstLapTime float64 `yaml:"DriverCarEstLapTime"`
DriverSetupName string `yaml:"DriverSetupName"`
DriverSetupIsModified int `yaml:"DriverSetupIsModified"`
DriverSetupLoadTypeName string `yaml:"DriverSetupLoadTypeName"`
DriverSetupPassedTech int `yaml:"DriverSetupPassedTech"`
DriverIncidentCount int `yaml:"DriverIncidentCount"`
Drivers []Driver `yaml:"Drivers"`
} `yaml:"DriverInfo"`
SplitTimeInfo struct {
Sectors []struct {
SectorNum int `yaml:"SectorNum"`
SectorStartPct float64 `yaml:"SectorStartPct"`
} `yaml:"Sectors"`
} `yaml:"SplitTimeInfo"`
CarSetup struct {
UpdateCount int `yaml:"UpdateCount"`
TiresAero struct {
LeftFront struct {
StartingPressure string `yaml:"StartingPressure"`
LastHotPressure string `yaml:"LastHotPressure"`
LastTempsOMI string `yaml:"LastTempsOMI"`
TreadRemaining string `yaml:"TreadRemaining"`
} `yaml:"LeftFront"`
LeftRear struct {
StartingPressure string `yaml:"StartingPressure"`
LastHotPressure string `yaml:"LastHotPressure"`
LastTempsOMI string `yaml:"LastTempsOMI"`
TreadRemaining string `yaml:"TreadRemaining"`
} `yaml:"LeftRear"`
RightFront struct {
StartingPressure string `yaml:"StartingPressure"`
LastHotPressure string `yaml:"LastHotPressure"`
LastTempsIMO string `yaml:"LastTempsIMO"`
TreadRemaining string `yaml:"TreadRemaining"`
} `yaml:"RightFront"`
RightRear struct {
StartingPressure string `yaml:"StartingPressure"`
LastHotPressure string `yaml:"LastHotPressure"`
LastTempsIMO string `yaml:"LastTempsIMO"`
TreadRemaining string `yaml:"TreadRemaining"`
} `yaml:"RightRear"`
} `yaml:"TiresAero"`
Chassis struct {
Front struct {
ArbSetting int `yaml:"ArbSetting"`
ToeIn string `yaml:"ToeIn"`
FuelLevel string `yaml:"FuelLevel"`
CrossWeight string `yaml:"CrossWeight"`
} `yaml:"Front"`
LeftFront struct {
CornerWeight string `yaml:"CornerWeight"`
RideHeight string `yaml:"RideHeight"`
SpringPerchOffset string `yaml:"SpringPerchOffset"`
Camber string `yaml:"Camber"`
} `yaml:"LeftFront"`
LeftRear struct {
CornerWeight string `yaml:"CornerWeight"`
RideHeight string `yaml:"RideHeight"`
SpringPerchOffset string `yaml:"SpringPerchOffset"`
Camber string `yaml:"Camber"`
ToeIn string `yaml:"ToeIn"`
} `yaml:"LeftRear"`
InCarDials struct {
DisplayPage string `yaml:"DisplayPage"`
BrakePressureBias string `yaml:"BrakePressureBias"`
} `yaml:"InCarDials"`
RightFront struct {
CornerWeight string `yaml:"CornerWeight"`
RideHeight string `yaml:"RideHeight"`
SpringPerchOffset string `yaml:"SpringPerchOffset"`
Camber string `yaml:"Camber"`
} `yaml:"RightFront"`
RightRear struct {
CornerWeight string `yaml:"CornerWeight"`
RideHeight string `yaml:"RideHeight"`
SpringPerchOffset string `yaml:"SpringPerchOffset"`
Camber string `yaml:"Camber"`
ToeIn string `yaml:"ToeIn"`
} `yaml:"RightRear"`
Rear struct {
ArbSetting int `yaml:"ArbSetting"`
WingSetting int `yaml:"WingSetting"`
} `yaml:"Rear"`
} `yaml:"Chassis"`
} `yaml:"CarSetup"`
}
// Driver ...
type Driver struct {
CarIdx int `yaml:"CarIdx"`
UserName string `yaml:"UserName"`
AbbrevName string `yaml:"AbbrevName"`
Initials string `yaml:"Initials"`
UserID int `yaml:"UserID"`
TeamID int `yaml:"TeamID"`
TeamName string `yaml:"TeamName"`
CarNumber string `yaml:"CarNumber"`
CarNumberRaw int `yaml:"CarNumberRaw"`
CarPath string `yaml:"CarPath"`
CarClassID int `yaml:"CarClassID"`
CarID int `yaml:"CarID"`
CarIsPaceCar int `yaml:"CarIsPaceCar"`
CarIsAI int `yaml:"CarIsAI"`
CarScreenName string `yaml:"CarScreenName"`
CarScreenNameShort string `yaml:"CarScreenNameShort"`
CarClassShortName string `yaml:"CarClassShortName"`
CarClassRelSpeed int `yaml:"CarClassRelSpeed"`
CarClassLicenseLevel int `yaml:"CarClassLicenseLevel"`
CarClassMaxFuelPct string `yaml:"CarClassMaxFuelPct"`
CarClassWeightPenalty string `yaml:"CarClassWeightPenalty"`
CarClassPowerAdjust string `yaml:"CarClassPowerAdjust"`
CarClassDryTireSetLimit string `yaml:"CarClassDryTireSetLimit"`
CarClassColor int `yaml:"CarClassColor"`
CarClassEstLapTime float64 `yaml:"CarClassEstLapTime"`
IRating int `yaml:"IRating"`
LicLevel int `yaml:"LicLevel"`
LicSubLevel int `yaml:"LicSubLevel"`
LicString string `yaml:"LicString"`
LicColor string `yaml:"LicColor"`
IsSpectator int `yaml:"IsSpectator"`
CarDesignStr string `yaml:"CarDesignStr"`
HelmetDesignStr string `yaml:"HelmetDesignStr"`
SuitDesignStr string `yaml:"SuitDesignStr"`
CarNumberDesignStr string `yaml:"CarNumberDesignStr"`
CarSponsor1 int `yaml:"CarSponsor_1"`
CarSponsor2 int `yaml:"CarSponsor_2"`
CurDriverIncidentCount int `yaml:"CurDriverIncidentCount"`
TeamIncidentCount int `yaml:"TeamIncidentCount"`
}
// parseSessionInfo will parse the sessionInfo buffer into the SessionInfoYAML
// struct
func parseSessionInfo(data []byte) (*SessionInfoYAML, error) {
var sessionInfo SessionInfoYAML
err := yaml.Unmarshal(data, &sessionInfo)
if err != nil {
return nil, err
}
return &sessionInfo, nil
}
// ToString will return a readable string of the struct
func (s *SessionInfoYAML) ToString() string {
stringified, _ := json.MarshalIndent(s, "", " ")
return string(stringified)
}
package goirsdk
import (
"encoding/json"
"fmt"
"log"
"strings"
"github.com/ESilva15/goirsdk/logger"
"golang.org/x/text/encoding/charmap"
"gopkg.in/yaml.v3"
)
// SessionInfoYAML is a string with session info in the IBT file
type SessionInfoYAML struct {
WeekendInfo struct {
TrackName string `yaml:"TrackName"`
TrackID int `yaml:"TrackID"`
TrackLength string `yaml:"TrackLength"`
TrackDisplayName string `yaml:"TrackDisplayName"`
TrackDisplayShortName string `yaml:"TrackDisplayShortName"`
TrackConfigName string `yaml:"TrackConfigName"`
TrackCity string `yaml:"TrackCity"`
TrackCountry string `yaml:"TrackCountry"`
TrackAltitude string `yaml:"TrackAltitude"`
TrackLatitude string `yaml:"TrackLatitude"`
TrackLongitude string `yaml:"TrackLongitude"`
TrackNorthOffset string `yaml:"TrackNorthOffset"`
TrackNumTurns int `yaml:"TrackNumTurns"`
TrackPitSpeedLimit string `yaml:"TrackPitSpeedLimit"`
TrackType string `yaml:"TrackType"`
TrackDirection string `yaml:"TrackDirection"`
TrackWeatherType string `yaml:"TrackWeatherType"`
TrackSkies string `yaml:"TrackSkies"`
TrackSurfaceTemp string `yaml:"TrackSurfaceTemp"`
TrackAirTemp string `yaml:"TrackAirTemp"`
TrackAirPressure string `yaml:"TrackAirPressure"`
TrackWindVel string `yaml:"TrackWindVel"`
TrackWindDir string `yaml:"TrackWindDir"`
TrackRelativeHumidity string `yaml:"TrackRelativeHumidity"`
TrackFogLevel string `yaml:"TrackFogLevel"`
TrackCleanup int `yaml:"TrackCleanup"`
TrackDynamicTrack int `yaml:"TrackDynamicTrack"`
TrackVersion string `yaml:"TrackVersion"`
SeriesID int `yaml:"SeriesID"`
SeasonID int `yaml:"SeasonID"`
SessionID int `yaml:"SessionID"`
SubSessionID int `yaml:"SubSessionID"`
LeagueID int `yaml:"LeagueID"`
Official int `yaml:"Official"`
RaceWeek int `yaml:"RaceWeek"`
EventType string `yaml:"EventType"`
Category string `yaml:"Category"`
SimMode string `yaml:"SimMode"`
TeamRacing int `yaml:"TeamRacing"`
MinDrivers int `yaml:"MinDrivers"`
MaxDrivers int `yaml:"MaxDrivers"`
DCRuleSet string `yaml:"DCRuleSet"`
QualifierMustStartRace int `yaml:"QualifierMustStartRace"`
NumCarClasses int `yaml:"NumCarClasses"`
NumCarTypes int `yaml:"NumCarTypes"`
HeatRacing int `yaml:"HeatRacing"`
BuildType string `yaml:"BuildType"`
BuildTarget string `yaml:"BuildTarget"`
BuildVersion string `yaml:"BuildVersion"`
WeekendOptions struct {
NumStarters int `yaml:"NumStarters"`
StartingGrid string `yaml:"StartingGrid"`
QualifyScoring string `yaml:"QualifyScoring"`
CourseCautions string `yaml:"CourseCautions"`
StandingStart int `yaml:"StandingStart"`
ShortParadeLap int `yaml:"ShortParadeLap"`
Restarts string `yaml:"Restarts"`
WeatherType string `yaml:"WeatherType"`
Skies string `yaml:"Skies"`
WindDirection string `yaml:"WindDirection"`
WindSpeed string `yaml:"WindSpeed"`
WeatherTemp string `yaml:"WeatherTemp"`
RelativeHumidity string `yaml:"RelativeHumidity"`
FogLevel string `yaml:"FogLevel"`
TimeOfDay string `yaml:"TimeOfDay"`
Date string `yaml:"Date"`
EarthRotationSpeedupFactor int `yaml:"EarthRotationSpeedupFactor"`
Unofficial int `yaml:"Unofficial"`
CommercialMode string `yaml:"CommercialMode"`
NightMode string `yaml:"NightMode"`
IsFixedSetup int `yaml:"IsFixedSetup"`
StrictLapsChecking string `yaml:"StrictLapsChecking"`
HasOpenRegistration int `yaml:"HasOpenRegistration"`
HardcoreLevel int `yaml:"HardcoreLevel"`
NumJokerLaps int `yaml:"NumJokerLaps"`
IncidentLimit string `yaml:"IncidentLimit"`
FastRepairsLimit string `yaml:"FastRepairsLimit"`
GreenWhiteCheckeredLimit int `yaml:"GreenWhiteCheckeredLimit"`
} `yaml:"WeekendOptions"`
TelemetryOptions struct {
TelemetryDiskFile string `yaml:"TelemetryDiskFile"`
} `yaml:"TelemetryOptions"`
} `yaml:"WeekendInfo"`
SessionInfo struct {
Sessions []struct {
SessionNum int `yaml:"SessionNum"`
SessionLaps string `yaml:"SessionLaps"`
SessionTime string `yaml:"SessionTime"`
SessionNumLapsToAvg int `yaml:"SessionNumLapsToAvg"`
SessionType string `yaml:"SessionType"`
SessionTrackRubberState string `yaml:"SessionTrackRubberState"`
SessionName string `yaml:"SessionName"`
SessionSubType interface{} `yaml:"SessionSubType"`
SessionSkipped int `yaml:"SessionSkipped"`
SessionRunGroupsUsed int `yaml:"SessionRunGroupsUsed"`
ResultsPositions interface{} `yaml:"ResultsPositions"`
ResultsFastestLap []struct {
CarIdx int `yaml:"CarIdx"`
FastestLap int `yaml:"FastestLap"`
FastestTime int `yaml:"FastestTime"`
} `yaml:"ResultsFastestLap"`
ResultsAverageLapTime int `yaml:"ResultsAverageLapTime"`
ResultsNumCautionFlags int `yaml:"ResultsNumCautionFlags"`
ResultsNumCautionLaps int `yaml:"ResultsNumCautionLaps"`
ResultsNumLeadChanges int `yaml:"ResultsNumLeadChanges"`
ResultsLapsComplete int `yaml:"ResultsLapsComplete"`
ResultsOfficial int `yaml:"ResultsOfficial"`
} `yaml:"Sessions"`
} `yaml:"SessionInfo"`
CameraInfo struct {
Groups []struct {
GroupNum int `yaml:"GroupNum"`
GroupName string `yaml:"GroupName"`
Cameras []struct {
CameraNum int `yaml:"CameraNum"`
CameraName string `yaml:"CameraName"`
} `yaml:"Cameras"`
IsScenic bool `yaml:"IsScenic,omitempty"`
} `yaml:"Groups"`
} `yaml:"CameraInfo"`
RadioInfo struct {
SelectedRadioNum int `yaml:"SelectedRadioNum"`
Radios []struct {
RadioNum int `yaml:"RadioNum"`
HopCount int `yaml:"HopCount"`
NumFrequencies int `yaml:"NumFrequencies"`
TunedToFrequencyNum int `yaml:"TunedToFrequencyNum"`
ScanningIsOn int `yaml:"ScanningIsOn"`
Frequencies []struct {
FrequencyNum int `yaml:"FrequencyNum"`
FrequencyName string `yaml:"FrequencyName"`
Priority int `yaml:"Priority"`
CarIdx int `yaml:"CarIdx"`
EntryIdx int `yaml:"EntryIdx"`
ClubID int `yaml:"ClubID"`
CanScan int `yaml:"CanScan"`
CanSquawk int `yaml:"CanSquawk"`
Muted int `yaml:"Muted"`
IsMutable int `yaml:"IsMutable"`
IsDeletable int `yaml:"IsDeletable"`
} `yaml:"Frequencies"`
} `yaml:"Radios"`
} `yaml:"RadioInfo"`
DriverInfo struct {
DriverCarIdx int `yaml:"DriverCarIdx"`
DriverUserID int `yaml:"DriverUserID"`
PaceCarIdx int `yaml:"PaceCarIdx"`
DriverHeadPosX float64 `yaml:"DriverHeadPosX"`
DriverHeadPosY float64 `yaml:"DriverHeadPosY"`
DriverHeadPosZ float64 `yaml:"DriverHeadPosZ"`
DriverCarIdleRPM float64 `yaml:"DriverCarIdleRPM"`
DriverCarRedLine float64 `yaml:"DriverCarRedLine"`
DriverCarEngCylinderCount int `yaml:"DriverCarEngCylinderCount"`
DriverCarFuelKgPerLtr float64 `yaml:"DriverCarFuelKgPerLtr"`
DriverCarFuelMaxLtr float64 `yaml:"DriverCarFuelMaxLtr"`
DriverCarMaxFuelPct float64 `yaml:"DriverCarMaxFuelPct"`
DriverCarGearNumForward int `yaml:"DriverCarGearNumForward"`
DriverCarGearNeutral int `yaml:"DriverCarGearNeutral"`
DriverCarGearReverse int `yaml:"DriverCarGearReverse"`
DriverCarSLFirstRPM float64 `yaml:"DriverCarSLFirstRPM"`
DriverCarSLShiftRPM float64 `yaml:"DriverCarSLShiftRPM"`
DriverCarSLLastRPM float64 `yaml:"DriverCarSLLastRPM"`
DriverCarSLBlinkRPM float64 `yaml:"DriverCarSLBlinkRPM"`
DriverCarVersion string `yaml:"DriverCarVersion"`
DriverPitTrkPct float64 `yaml:"DriverPitTrkPct"`
DriverCarEstLapTime float64 `yaml:"DriverCarEstLapTime"`
DriverSetupName string `yaml:"DriverSetupName"`
DriverSetupIsModified int `yaml:"DriverSetupIsModified"`
DriverSetupLoadTypeName string `yaml:"DriverSetupLoadTypeName"`
DriverSetupPassedTech int `yaml:"DriverSetupPassedTech"`
DriverIncidentCount int `yaml:"DriverIncidentCount"`
Drivers []Driver `yaml:"Drivers"`
} `yaml:"DriverInfo"`
SplitTimeInfo struct {
Sectors []struct {
SectorNum int `yaml:"SectorNum"`
SectorStartPct float64 `yaml:"SectorStartPct"`
} `yaml:"Sectors"`
} `yaml:"SplitTimeInfo"`
CarSetup struct {
UpdateCount int `yaml:"UpdateCount"`
TiresAero struct {
LeftFront struct {
StartingPressure string `yaml:"StartingPressure"`
LastHotPressure string `yaml:"LastHotPressure"`
LastTempsOMI string `yaml:"LastTempsOMI"`
TreadRemaining string `yaml:"TreadRemaining"`
} `yaml:"LeftFront"`
LeftRear struct {
StartingPressure string `yaml:"StartingPressure"`
LastHotPressure string `yaml:"LastHotPressure"`
LastTempsOMI string `yaml:"LastTempsOMI"`
TreadRemaining string `yaml:"TreadRemaining"`
} `yaml:"LeftRear"`
RightFront struct {
StartingPressure string `yaml:"StartingPressure"`
LastHotPressure string `yaml:"LastHotPressure"`
LastTempsIMO string `yaml:"LastTempsIMO"`
TreadRemaining string `yaml:"TreadRemaining"`
} `yaml:"RightFront"`
RightRear struct {
StartingPressure string `yaml:"StartingPressure"`
LastHotPressure string `yaml:"LastHotPressure"`
LastTempsIMO string `yaml:"LastTempsIMO"`
TreadRemaining string `yaml:"TreadRemaining"`
} `yaml:"RightRear"`
} `yaml:"TiresAero"`
Chassis struct {
Front struct {
ArbSetting int `yaml:"ArbSetting"`
ToeIn string `yaml:"ToeIn"`
FuelLevel string `yaml:"FuelLevel"`
CrossWeight string `yaml:"CrossWeight"`
} `yaml:"Front"`
LeftFront struct {
CornerWeight string `yaml:"CornerWeight"`
RideHeight string `yaml:"RideHeight"`
SpringPerchOffset string `yaml:"SpringPerchOffset"`
Camber string `yaml:"Camber"`
} `yaml:"LeftFront"`
LeftRear struct {
CornerWeight string `yaml:"CornerWeight"`
RideHeight string `yaml:"RideHeight"`
SpringPerchOffset string `yaml:"SpringPerchOffset"`
Camber string `yaml:"Camber"`
ToeIn string `yaml:"ToeIn"`
} `yaml:"LeftRear"`
InCarDials struct {
DisplayPage string `yaml:"DisplayPage"`
BrakePressureBias string `yaml:"BrakePressureBias"`
} `yaml:"InCarDials"`
RightFront struct {
CornerWeight string `yaml:"CornerWeight"`
RideHeight string `yaml:"RideHeight"`
SpringPerchOffset string `yaml:"SpringPerchOffset"`
Camber string `yaml:"Camber"`
} `yaml:"RightFront"`
RightRear struct {
CornerWeight string `yaml:"CornerWeight"`
RideHeight string `yaml:"RideHeight"`
SpringPerchOffset string `yaml:"SpringPerchOffset"`
Camber string `yaml:"Camber"`
ToeIn string `yaml:"ToeIn"`
} `yaml:"RightRear"`
Rear struct {
ArbSetting int `yaml:"ArbSetting"`
WingSetting int `yaml:"WingSetting"`
} `yaml:"Rear"`
} `yaml:"Chassis"`
} `yaml:"CarSetup"`
}
// Driver ...
type Driver struct {
CarIdx int `yaml:"CarIdx"`
UserName string `yaml:"UserName"`
AbbrevName string `yaml:"AbbrevName"`
Initials string `yaml:"Initials"`
UserID int `yaml:"UserID"`
TeamID int `yaml:"TeamID"`
TeamName string `yaml:"TeamName"`
CarNumber string `yaml:"CarNumber"`
CarNumberRaw int `yaml:"CarNumberRaw"`
CarPath string `yaml:"CarPath"`
CarClassID int `yaml:"CarClassID"`
CarID int `yaml:"CarID"`
CarIsPaceCar int `yaml:"CarIsPaceCar"`
CarIsAI int `yaml:"CarIsAI"`
CarScreenName string `yaml:"CarScreenName"`
CarScreenNameShort string `yaml:"CarScreenNameShort"`
CarClassShortName string `yaml:"CarClassShortName"`
CarClassRelSpeed int `yaml:"CarClassRelSpeed"`
CarClassLicenseLevel int `yaml:"CarClassLicenseLevel"`
CarClassMaxFuelPct string `yaml:"CarClassMaxFuelPct"`
CarClassWeightPenalty string `yaml:"CarClassWeightPenalty"`
CarClassPowerAdjust string `yaml:"CarClassPowerAdjust"`
CarClassDryTireSetLimit string `yaml:"CarClassDryTireSetLimit"`
CarClassColor int `yaml:"CarClassColor"`
CarClassEstLapTime float64 `yaml:"CarClassEstLapTime"`
IRating int `yaml:"IRating"`
LicLevel int `yaml:"LicLevel"`
LicSubLevel int `yaml:"LicSubLevel"`
LicString string `yaml:"LicString"`
LicColor string `yaml:"LicColor"`
IsSpectator int `yaml:"IsSpectator"`
CarDesignStr string `yaml:"CarDesignStr"`
HelmetDesignStr string `yaml:"HelmetDesignStr"`
SuitDesignStr string `yaml:"SuitDesignStr"`
CarNumberDesignStr string `yaml:"CarNumberDesignStr"`
CarSponsor1 int `yaml:"CarSponsor_1"`
CarSponsor2 int `yaml:"CarSponsor_2"`
CurDriverIncidentCount int `yaml:"CurDriverIncidentCount"`
TeamIncidentCount int `yaml:"TeamIncidentCount"`
}
// readSessionInfo will read the session info yaml out of the telemetry data
func (i *IBT) readSessionInfo() error {
log := logger.GetInstance()
sessionInfoStringRaw := make([]byte, i.Headers.SessionInfoLength)
_, err := i.File.ReadAt(sessionInfoStringRaw, int64(i.Headers.SessionInfoOffset))
if err != nil {
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 {
log.Printf("Failed to export YAML string: %v\n", err)
}
}
return nil
}
// parseSessionInfo will parse the sessionInfo buffer into the SessionInfoYAML
// struct
func parseSessionInfo(buf []byte, len int32) (*SessionInfoYAML, error) {
// this seems not to work on windows
// windows := true
var sessionInfo SessionInfoYAML
dataBuffer := buf
// FOR WINDOWS
// if windows {
decoder := charmap.Windows1252.NewDecoder()
buf, err := decoder.Bytes(buf)
if err != nil {
log.Fatal(err)
}
dataBuffer = []byte(strings.TrimRight(string(buf[:len]), "\x00"))
// }
err = yaml.Unmarshal(dataBuffer, &sessionInfo)
if err != nil {
return nil, err
}
return &sessionInfo, nil
}
// sessionStatusOK will tell us if we are connected to the live data
func sessionStatusOK(status int) bool {
return (status & stConnected) > 0
}
// ToString will return a readable string of the struct
func (s *SessionInfoYAML) ToString() string {
stringified, _ := json.MarshalIndent(s, "", " ")
return string(stringified)
}
+88
View File
@@ -0,0 +1,88 @@
package sharedMem
import (
"fmt"
"io"
)
// Memory is shared memory struct
type Memory struct {
m *shmi
pos int64
}
// Create is create shared memory
func Create(name string, size uint32) (*Memory, error) {
m, err := create(name, size)
if err != nil {
return nil, err
}
return &Memory{m, 0}, nil
}
// Open is open exist shared memory
func Open(name string, size uint32) (*Memory, error) {
m, err := open(name, size)
if err != nil {
return nil, err
}
return &Memory{m, 0}, nil
}
// Close is close & discard shared memory
func (o *Memory) Close() (err error) {
if o.m != nil {
err = o.m.close()
if err == nil {
o.m = nil
}
}
return err
}
// Read is read shared memory (current position)
func (o *Memory) Read(p []byte) (n int, err error) {
n, err = o.ReadAt(p, o.pos)
if err != nil {
return 0, err
}
o.pos += int64(n)
return n, nil
}
// ReadAt is read shared memory (offset)
func (o *Memory) ReadAt(p []byte, off int64) (n int, err error) {
return o.m.readAt(p, off)
}
// Seek is move read/write position at shared memory
func (o *Memory) Seek(offset int64, whence int) (int64, error) {
switch whence {
case io.SeekStart:
offset += int64(0)
case io.SeekCurrent:
offset += o.pos
case io.SeekEnd:
offset += int64(o.m.size)
}
if offset < 0 || offset >= int64(o.m.size) {
return 0, fmt.Errorf("invalid offset")
}
o.pos = offset
return offset, nil
}
// Write is write shared memory (current position)
func (o *Memory) Write(p []byte) (n int, err error) {
n, err = o.WriteAt(p, o.pos)
if err != nil {
return 0, err
}
o.pos += int64(n)
return n, nil
}
// WriteAt is write shared memory (offset)
func (o *Memory) WriteAt(p []byte, off int64) (n int, err error) {
return o.m.writeAt(p, off)
}
+157
View File
@@ -0,0 +1,157 @@
//go:build darwin && cgo
// +build darwin,cgo
package sharedMem
/*
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/errno.h>
int _create(const char* name, int size, int flag) {
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
int fd = shm_open(name, flag, mode);
if (fd < 0) {
return -1;
}
struct stat mapstat;
int ret = fstat(fd, &mapstat);
if (ret != -1 && mapstat.st_size == 0) {
if (ftruncate(fd, size) != 0) {
close(fd);
return -2;
}
} else if (ret == -1) {
close(fd);
return -3;
}
return fd;
}
int Create(const char* name, int size) {
int flag = O_RDWR | O_CREAT;
return _create(name, size, flag);
}
int Open(const char* name, int size) {
int flag = O_RDWR;
return _create(name, size, flag);
}
void* Map(int fd, int size) {
void* p = mmap(
NULL, size,
PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (p == MAP_FAILED) {
return NULL;
}
return p;
}
void Close(int fd, void* p, int size) {
if (p != NULL) {
munmap(p, size);
}
if (fd != 0) {
close(fd);
}
}
void Delete(const char* name) {
shm_unlink(name);
}
*/
import "C"
import (
"fmt"
"io"
"unsafe"
)
type shmi struct {
name string
fd C.int
v unsafe.Pointer
size uint32
parent bool
}
// create shared memory. return shmi object.
// name should not be more than 31 bytes.
func create(name string, size uint32) (*shmi, error) {
name = "/" + name
fd := C.Create(C.CString(name), C.int(size))
if fd < 0 {
return nil, fmt.Errorf("create")
}
v := C.Map(fd, C.int(size))
if v == nil {
C.Close(fd, nil, C.int(size))
C.Delete(C.CString(name))
}
return &shmi{name, fd, v, size, true}, nil
}
// open shared memory. return shmi object.
// name should not be more than 31 bytes.
func open(name string, size uint32) (*shmi, error) {
name = "/" + name
fd := C.Open(C.CString(name), C.int(size))
if fd < 0 {
return nil, fmt.Errorf("open")
}
v := C.Map(fd, C.int(size))
if v == nil {
C.Close(fd, nil, C.int(size))
C.Delete(C.CString(name))
}
return &shmi{name, fd, v, size, false}, nil
}
func (o *shmi) close() error {
if o.v != nil {
C.Close(o.fd, o.v, C.int(o.size))
o.v = nil
}
if o.parent {
C.Delete(C.CString(o.name))
}
return nil
}
// read shared memory. return read size.
func (o *shmi) readAt(p []byte, off int64) (n int, err error) {
if off >= int64(o.size) {
return 0, io.EOF
}
if max := int64(o.size) - off; int64(len(p)) > max {
p = p[:max]
}
return copyPtr2Slice(uintptr(o.v), p, off, o.size), nil
}
// write shared memory. return write size.
func (o *shmi) writeAt(p []byte, off int64) (n int, err error) {
if off >= int64(o.size) {
return 0, io.EOF
}
if max := int64(o.size) - off; int64(len(p)) > max {
p = p[:max]
}
return copySlice2Ptr(p, uintptr(o.v), off, o.size), nil
}
+148
View File
@@ -0,0 +1,148 @@
//go:build linux && cgo
// +build linux,cgo
package sharedMem
/*
#cgo LDFLAGS: -lrt
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int _create(const char* name, int size, int flag) {
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
int fd = shm_open(name, flag, mode);
if (fd < 0) {
return -1;
}
if (ftruncate(fd, size) != 0) {
close(fd);
return -2;
}
return fd;
}
int Create(const char* name, int size) {
int flag = O_RDWR | O_CREAT;
return _create(name, size, flag);
}
int Open(const char* name, int size) {
int flag = O_RDWR;
return _create(name, size, flag);
}
void* Map(int fd, int size) {
void* p = mmap(
NULL, size,
PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (p == MAP_FAILED) {
return NULL;
}
return p;
}
void Close(int fd, void* p, int size) {
if (p != NULL) {
munmap(p, size);
}
if (fd != 0) {
close(fd);
}
}
void Delete(const char* name) {
shm_unlink(name);
}
*/
import "C"
import (
"fmt"
"io"
"unsafe"
)
type shmi struct {
name string
fd C.int
v unsafe.Pointer
size uint32
parent bool
}
// create shared memory. return shmi object.
func create(name string, size uint32) (*shmi, error) {
name = "/" + name
fd := C.Create(C.CString(name), C.int(size))
if fd < 0 {
return nil, fmt.Errorf("create")
}
v := C.Map(fd, C.int(size))
if v == nil {
C.Close(fd, nil, C.int(size))
C.Delete(C.CString(name))
}
return &shmi{name, fd, v, size, true}, nil
}
// open shared memory. return shmi object.
func open(name string, size uint32) (*shmi, error) {
name = "/" + name
fd := C.Open(C.CString(name), C.int(size))
if fd < 0 {
return nil, fmt.Errorf("open")
}
v := C.Map(fd, C.int(size))
if v == nil {
C.Close(fd, nil, C.int(size))
C.Delete(C.CString(name))
}
return &shmi{name, fd, v, size, false}, nil
}
func (o *shmi) close() error {
if o.v != nil {
C.Close(o.fd, o.v, C.int(o.size))
o.v = nil
}
if o.parent {
C.Delete(C.CString(o.name))
}
return nil
}
// read shared memory. return read size.
func (o *shmi) readAt(p []byte, off int64) (n int, err error) {
if off >= int64(o.size) {
return 0, io.EOF
}
if max := int64(o.size) - off; int64(len(p)) > max {
p = p[:max]
}
return copyPtr2Slice(uintptr(o.v), p, off, o.size), nil
}
// write shared memory. return write size.
func (o *shmi) writeAt(p []byte, off int64) (n int, err error) {
if off >= int64(o.size) {
return 0, io.EOF
}
if max := int64(o.size) - off; int64(len(p)) > max {
p = p[:max]
}
return copySlice2Ptr(p, uintptr(o.v), off, o.size), nil
}
+85
View File
@@ -0,0 +1,85 @@
//go:build windows && cgo
// +build windows,cgo
package sharedMem
import (
"io"
"log"
"golang.org/x/sys/windows"
)
type shmi struct {
h windows.Handle
v uintptr
size uint32
}
// create shared memory. return shmi object.
func create(name string, size uint32) (*shmi, error) {
fnPtr, _ := windows.UTF16PtrFromString(name)
flProtect := uint32(windows.PAGE_READONLY)
h, errno := windows.CreateFileMapping(
windows.InvalidHandle,
nil,
flProtect,
0,
size,
fnPtr)
if h == 0 {
log.Fatal("could not open memmap file: ", errno)
}
addr, errno := windows.MapViewOfFile(h,
windows.FILE_MAP_READ,
0,
0,
uintptr(size))
if addr == 0 {
log.Printf("error in MapViewOfFile: %v", errno)
}
return &shmi{h, addr, size}, nil
}
// open shared memory. return shmi object.
func open(name string, size uint32) (*shmi, error) {
return create(name, size)
}
func (o *shmi) close() error {
if o.v != uintptr(0) {
windows.UnmapViewOfFile(o.v)
o.v = uintptr(0)
}
if o.h != windows.InvalidHandle {
windows.CloseHandle(o.h)
o.h = windows.InvalidHandle
}
return nil
}
// read shared memory. return read size.
func (o *shmi) readAt(p []byte, off int64) (n int, err error) {
if off >= int64(o.size) {
return 0, io.EOF
}
if max := int64(o.size) - off; int64(len(p)) > max {
p = p[:max]
}
return copyPtr2Slice(o.v, p, off, o.size), nil
}
// write shared memory. return write size.
func (o *shmi) writeAt(p []byte, off int64) (n int, err error) {
if off >= int64(o.size) {
return 0, io.EOF
}
if max := int64(o.size) - off; int64(len(p)) > max {
p = p[:max]
}
return copySlice2Ptr(p, o.v, off, o.size), nil
}
+15
View File
@@ -0,0 +1,15 @@
package sharedMem
import (
"unsafe"
)
func copySlice2Ptr(b []byte, p uintptr, off int64, size uint32) int {
bb := unsafe.Slice((*byte)(*(*unsafe.Pointer)(unsafe.Pointer(&p))), int(size))
return copy(bb[off:], b)
}
func copyPtr2Slice(p uintptr, b []byte, off int64, size uint32) int {
bb := unsafe.Slice((*byte)(*(*unsafe.Pointer)(unsafe.Pointer(&p))), int(size))
return copy(b, bb[off:size])
}
Binary file not shown.
Binary file not shown.
+19
View File
@@ -0,0 +1,19 @@
package utils
import "fmt"
func HexDump(buf []byte) {
fmt.Printf("\n============ HEX DUMP =============\n")
for k := 0; k < len(buf); k++ {
if k%4 == 0 && k > 0 {
fmt.Printf(" ")
}
if k%16 == 0 && k > 0 {
fmt.Printf("\n")
}
fmt.Printf("%02X", buf[k])
}
fmt.Printf("\n============ HEX DUMP =============\n")
}
+420 -177
View File
@@ -1,177 +1,420 @@
package ibtReader
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"log"
"math"
"strings"
)
const (
VarHeaderSize = 144
IRSDK_char = 0
IRSDK_bool = 1
IRSDK_int = 2
IRSDK_bitField = 3
IRSDK_float = 4
IRSDK_double = 5
)
// I think I can make an interface if IRSDK types with available types and
// that they need a parser (reads and type coerces I guess)
var (
VarTypes = map[int]VarType{
IRSDK_char: {1, "irsdk_char"},
IRSDK_bool: {1, "irsdk_bool"},
IRSDK_int: {4, "irsdk_int"},
IRSDK_bitField: {4, "irsdk_bitField"},
IRSDK_float: {4, "irsdk_float"},
IRSDK_double: {8, "irsdk_double"},
}
)
type VarType struct {
Size int // Size is the var type size in bytes
Name string // Name is the irsdk var name
}
type IBTVar struct {
Type int32
Offset int32
Count int32
CountAsTime bool
Padding [3]byte
Name [32]byte
Description [64]byte
Unit [32]byte
}
type Var struct {
Type int32
Offset int32
Count int32
CountAsTime bool
Name string
Description string
Unit string
// TODO
// Create an interface for this value
// Represent the IRSDK var types with a struct each that implements the Parse
// method or something like that I guess
Value interface{}
}
func (v *IBTVar) 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,
)
}
type varBuffer struct {
tickCount int
bufOffset int
}
type TelemetryVars struct {
LastVersion int
Vars map[string]Var
}
func (i *IBT) readVariablerHeaders() error {
i.Vars = &TelemetryVars{Vars: make(map[string]Var, i.Headers.NumVars)}
var k int32
for k = 0; k < i.Headers.NumVars; k++ {
rbuf := make([]byte, VarHeaderSize)
_, err := i.File.ReadAt(rbuf, int64(i.Headers.VarHeaderOffset+k*VarHeaderSize))
if err != nil {
return err
}
var dst IBTVar
err = binary.Read(bytes.NewBuffer(rbuf[:]), binary.LittleEndian, &dst)
if err != nil {
return err
}
v := Var{
Type: dst.Type,
Offset: dst.Offset,
Count: dst.Count,
CountAsTime: dst.CountAsTime,
Name: strings.TrimRight(string(dst.Name[:]), "\x00"),
Description: strings.TrimRight(string(dst.Description[:]), "\x00"),
Unit: strings.TrimRight(string(dst.Unit[:]), "\x00"),
Value: nil,
}
i.Vars.Vars[v.Name] = v
}
return nil
}
func (i *IBT) readData() error {
// I think that we can add one extra check or verification here
// The file headers tells us how many data frames there are, we can probably
// cap it at that instead of waiting for the read to fail
// Probably wouldn't work on live data tho
start := i.Headers.BufOffset + i.Tick*i.Headers.BufLen
buf := make([]byte, i.Headers.BufLen)
_, err := i.File.ReadAt(buf, int64(start))
if err != nil {
return err
}
for k, v := range i.Vars.Vars {
rbuf := buf[v.Offset : v.Offset+int32(VarTypes[int(v.Type)].Size)]
// Read the value
switch v.Type {
case IRSDK_char:
v.Value = string(rbuf[0])
case IRSDK_bool:
v.Value = int(rbuf[0]) > 0
case IRSDK_int:
v.Value = int(binary.LittleEndian.Uint32(rbuf))
case IRSDK_bitField:
v.Value = fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
case IRSDK_float:
v.Value = math.Float32frombits(uint32(binary.LittleEndian.Uint32(rbuf)))
case IRSDK_double:
v.Value = math.Float64frombits(uint64(binary.LittleEndian.Uint64(rbuf)))
}
// --------------
i.Vars.Vars[k] = v
}
i.Tick++
return nil
}
func (i *IBT) Update() bool {
err := i.readData()
if err != nil && err != io.EOF {
log.Fatalf("What happened?\n%v\n", err)
}
if err == io.EOF {
return false
}
return true
}
package goirsdk
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"log"
"math"
"strconv"
"strings"
"time"
)
const (
VarHeaderSize = 144
IRSDK_char = 0
IRSDK_bool = 1
IRSDK_int = 2
IRSDK_bitField = 3
IRSDK_float = 4
IRSDK_double = 5
Running IRacingState = iota
Paused
Ended
Failed
Unknown
)
// I think I can make an interface if IRSDK types with available types and
// that they need a parser (reads and type coerces I guess)
var (
VarTypes = map[int]VarType{
IRSDK_char: {1, "irsdk_char"},
IRSDK_bool: {1, "irsdk_bool"},
IRSDK_int: {4, "irsdk_int"},
IRSDK_bitField: {4, "irsdk_bitField"},
IRSDK_float: {4, "irsdk_float"},
IRSDK_double: {8, "irsdk_double"},
}
)
type (
IRacingState int
VarType struct {
Size int // Size is the var type size in bytes
Name string // Name is the irsdk var name
}
)
type IBTVar struct {
Type int32
Offset int32
Count int32
CountAsTime bool
Padding [3]byte
Name [32]byte
Description [64]byte
Unit [32]byte
}
type Var struct {
Type int32
Offset int32
Count int32
CountAsTime bool
Name string
Description string
Unit string
// TODO
// Create an interface for this value
// Represent the IRSDK var types with a struct each that implements the Parse
// method or something like that I guess
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"+
"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,
)
}
type varBuffer struct {
TickCount int32
BufOffset int32
}
type TelemetryVars struct {
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
Vars map[string]Var // Variables content
}
func (i *IBT) readVariablerHeaders() error {
i.Vars = &TelemetryVars{Vars: make(map[string]Var, i.Headers.NumVars)}
var k int32
for k = 0; k < i.Headers.NumVars; k++ {
rbuf := make([]byte, VarHeaderSize)
_, err := i.File.ReadAt(rbuf, int64(i.Headers.VarHeaderOffset+k*VarHeaderSize))
if err != nil {
return err
}
if i.Opts.IBTExport {
err = i.exportIBT(rbuf, int64(i.Headers.VarHeaderOffset+k*VarHeaderSize))
if err != nil {
// Don't outright kill it here - maybe nowhere else
log.Printf("Failed to export variable contents: %v\n", err)
}
}
var dst IBTVar
err = binary.Read(bytes.NewBuffer(rbuf[:]), binary.LittleEndian, &dst)
if err != nil {
return err
}
v := Var{
Type: dst.Type,
Offset: dst.Offset,
Count: dst.Count,
CountAsTime: dst.CountAsTime,
Name: strings.TrimRight(string(dst.Name[:]), "\x00"),
Description: strings.TrimRight(string(dst.Description[:]), "\x00"),
Unit: strings.TrimRight(string(dst.Unit[:]), "\x00"),
Value: nil,
}
i.Vars.Vars[v.Name] = v
}
return nil
}
func (i *IBT) parseEngineWarnings() {
val, ok := i.Vars.Vars["EngineWarnings"]
if !ok {
log.Fatal("no engine warnings")
}
bitfield, err := strconv.ParseInt(val.Value.(string), 0, 64)
if err != nil {
log.Fatal("Unable to get engine warnings: " + err.Error())
}
for _, ew := range irsdkEngineWarnings {
result := (int(bitfield) & ew.Value) != 0
i.Vars.Vars[ew.Name] = Var{Value: result}
}
}
// parseBitfieldVariables will parse the variables:
// - irsdk_CameraState "CamCameraState"
// - irsdk_EngineWarnings "EngineWarnings"
// - irsdk_PitSvFlags "PitSvFlags"
// - irsdk_Flags "SessionFlags"
// - irsdk_SessionState "SessionState"
// - irsdk_TrkLoc "CarIdxTrackSurface"
//
// The approach for now will be to create unique entries in the data map for
// the fields in these variables
func (i *IBT) parseBitfieldVariables() {
// Parse the EngineWarnings variables - its the only one for now
i.parseEngineWarnings()
}
func (i *IBT) readData(buf []byte) error {
for k, v := range i.Vars.Vars {
// Slice of the variable value in the buffer
rbuf := buf[v.Offset : v.Offset+int32(VarTypes[int(v.Type)].Size)]
// Read the value
switch v.Type {
case IRSDK_char:
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:
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:
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:
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:
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:
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
}
// Parse the bitfield variables here
i.parseBitfieldVariables()
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) {
// This is what happens if we are reading live data
if i.winUtils != nil {
// Put a way to check if the sim is active here
// fmt.Println("NOT CHECKING IF SIM IS ACTIVE - ADD ME")
// WORKING HERE
// Need to figure out how to grab the latest buffer with data
var vb varBuffer
foundTickCount := 0
for k := 0; k < int(i.Headers.NumBuf); k++ {
rbuf := make([]byte, 16)
// Read 16 bytes, I don't know why, but do need to understand this
_, err := i.File.ReadAt(rbuf, int64(48+k*16))
if err != nil {
return Failed, err
}
var curVb varBuffer
err = binary.Read(bytes.NewBuffer(rbuf[:]), binary.LittleEndian, &curVb)
if err != nil {
return Failed, err
}
if foundTickCount < int(curVb.TickCount) {
foundTickCount = int(curVb.TickCount)
vb = curVb
}
}
i.Vars.Tick = vb.TickCount
start := vb.BufOffset
buf := make([]byte, i.Headers.BufLen)
_, err := i.File.ReadAt(buf, int64(start))
if err != nil {
return Failed, err
}
if i.Opts.IBTExport {
// Dirty attempt at getting this to work to write to a memory mapped file
switch i.Opts.IBTExportType {
case IBTFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset+i.Vars.RecorderTick*i.Headers.BufLen))
if err != nil {
log.Printf("Failed to export live telemetry data: %v", err)
}
case SharedMemoryFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset))
if err != nil {
log.Printf("Failed to export live telemetry data: %v", err)
}
}
}
err = i.readData(buf)
if err != nil && err != io.EOF {
return Unknown, err
}
if err == io.EOF {
return Ended, nil
}
// Document why this is here, I don't remember the exact words right now
i.Vars.RecorderTick++
} else {
// This is what happens if we are reading from an .ibt file
// This will get the dataframe corresponding to a given tick
start := i.Headers.BufOffset + i.Vars.Tick*i.Headers.BufLen
buf := make([]byte, i.Headers.BufLen)
_, 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
if i.Opts.IBTExport {
// Dirty attempt at getting this to work to write to a memory mapped file
switch i.Opts.IBTExportType {
case IBTFile:
err = i.exportIBT(buf, int64(start))
if err != nil {
log.Printf("Failed to export offline telemetry data: %v", err)
}
case SharedMemoryFile:
err = i.exportIBT(buf, int64(i.Headers.BufOffset))
if err != nil {
log.Printf("Failed to export live telemetry data: %v", err)
}
}
}
if err == io.EOF {
return Ended, nil
}
if err != nil {
return Unknown, err
}
err = i.readData(buf)
if err != nil && err != io.EOF {
log.Fatalf("What happened?\n%v\n", err)
}
// This was previously in the read data method, but it probably fits here better
i.Vars.Tick++
}
return Running, nil
}