Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b0283b206 | ||
|
|
a449ced75f | ||
|
|
9adc0a9456 | ||
|
|
76a091b076 | ||
|
|
b703933f08 | ||
|
|
6bcc0a1613 | ||
|
|
fa7f0b73ee | ||
|
|
c5ff9f95c9 | ||
|
|
4713fc80eb | ||
|
|
f102d74311 | ||
|
|
172fa4ff52 | ||
|
|
90a0321e9f | ||
|
|
6b595fabb1 | ||
|
|
4a56d253e5 | ||
|
|
a3418e0c95 | ||
|
|
45a0aa43aa | ||
|
|
38e7ea32cc | ||
|
|
bcbffdc7a2 | ||
|
|
2dc1771bb6 |
+2
-2
@@ -1,2 +1,2 @@
|
||||
coverage*
|
||||
*.txt
|
||||
coverage*
|
||||
*.txt
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
test:
|
||||
go test -coverprofile=coverage.out ./... -cover -bench=
|
||||
go tool cover -html=coverage.out -o coverage.html
|
||||
test:
|
||||
go test -coverprofile=coverage.out ./... -cover -bench=
|
||||
go tool cover -html=coverage.out -o coverage.html
|
||||
|
||||
@@ -1,17 +1,118 @@
|
||||
# About
|
||||
This project will be able to parse `.ibt` files, read live data from races and
|
||||
broadcast messages to the service. Its still not very mature at all, but after
|
||||
this commit I will turn it into a package instead and give it a stable API.
|
||||
Will also put some examples then.
|
||||
|
||||
|
||||
## The SDK
|
||||
I used various sources to develop and understand how `iRacing` works, and learn
|
||||
a lot with it. Once I have matured this project a bit I will document its
|
||||
inner workings too.
|
||||
|
||||
|
||||
## 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.
|
||||
# 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.
|
||||
|
||||
+26
-4
@@ -8,9 +8,10 @@ type Msg struct {
|
||||
}
|
||||
|
||||
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\\IRSDKMemMapFileName"
|
||||
IRSDK_MEMMAPFILENAME string = "Local\\" + MEMMAPFILENAME
|
||||
IRSDK_BROADCASTMSGNAME string = "IRSDK_BROADCASTMSG"
|
||||
fileMapSize uint32 = 1164 * 1024
|
||||
connTimeout int64 = 30
|
||||
@@ -116,10 +117,31 @@ const (
|
||||
// CamNose
|
||||
)
|
||||
|
||||
|
||||
// Some other constants that I need to get trough
|
||||
// // bit fields
|
||||
// enum irsdk_EngineWarnings
|
||||
|
||||
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,
|
||||
@@ -165,7 +187,7 @@ const (
|
||||
// };
|
||||
//
|
||||
//
|
||||
// // status
|
||||
// // status
|
||||
// enum irsdk_TrkLoc
|
||||
// {
|
||||
// irsdk_NotInWorld = -1,
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
|
||||
"github.com/ESilva15/goirsdk/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -19,6 +21,31 @@ type DiskSubHeader struct {
|
||||
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
|
||||
|
||||
@@ -1,38 +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)
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ go 1.23.2
|
||||
|
||||
require (
|
||||
github.com/google/go-cmp v0.6.0
|
||||
golang.org/x/sys v0.26.0
|
||||
golang.org/x/sys v0.29.0
|
||||
golang.org/x/text v0.19.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.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=
|
||||
|
||||
+55
-39
@@ -4,6 +4,8 @@ import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
|
||||
"github.com/ESilva15/goirsdk/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -13,30 +15,60 @@ const (
|
||||
|
||||
// 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
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -61,19 +93,3 @@ func (th *TelemetryHeaders) ToString() string {
|
||||
th.NumBuf, th.NumBuf, th.BufLen, th.BufLen, th.BufOffset, th.BufOffset,
|
||||
)
|
||||
}
|
||||
|
||||
// parseTelemetryHeader will read the IBT file headers from a correctly sized
|
||||
// buffer.
|
||||
// You need to pass a the first FILE_HEADER_SIZE bytes of the buffer
|
||||
func parseTelemetryHeader(buf [FileHeaderSize]byte) (*TelemetryHeaders, error) {
|
||||
// utils.HexDump(buf[:])
|
||||
// fmt.Printf("Len: %d\n", len(buf))
|
||||
|
||||
dst := TelemetryHeaders{}
|
||||
err := binary.Read(bytes.NewBuffer(buf[:]), binary.LittleEndian, &dst)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to unpack data: %v", err)
|
||||
}
|
||||
|
||||
return &dst, nil
|
||||
}
|
||||
|
||||
+52
-52
@@ -1,52 +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)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,19 +3,13 @@ package goirsdk
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
// "os"
|
||||
"io"
|
||||
// "log"
|
||||
// "time"
|
||||
"os"
|
||||
|
||||
// conv "ibtReader/conversions"
|
||||
"github.com/ESilva15/goirsdk/winutils"
|
||||
)
|
||||
|
||||
const (
|
||||
ibtFile = "./telemetryFiles/mx5_2016Okayama_full_2024_10_19_22_02_12.ibt"
|
||||
"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
|
||||
@@ -26,15 +20,47 @@ type Reader interface {
|
||||
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
|
||||
FileToExport string // If set, it will export the IBT data to the 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
|
||||
winUtils *winutils.IRacingWinUtils // WinUtils gives access to the system utilities
|
||||
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 {
|
||||
@@ -50,89 +76,151 @@ func (i *IBT) IsConnected() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (i *IBT) ExportToIBT(filepath string) {
|
||||
rbuf := make([]byte, fileMapSize)
|
||||
func (i *IBT) exportYAML() error {
|
||||
log := logger.GetInstance()
|
||||
|
||||
_, err := i.File.ReadAt(rbuf, 0)
|
||||
file, err := os.OpenFile(i.Opts.SessionInfoExportPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
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)
|
||||
}
|
||||
|
||||
err = os.WriteFile(filepath, rbuf, 0644)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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{},
|
||||
winUtils: 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
|
||||
}
|
||||
|
||||
if ibt.File == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *IBT) openSource() error {
|
||||
var err error
|
||||
|
||||
switch i.Opts.SourceType {
|
||||
case SharedMemoryFile:
|
||||
// User is requesting us to read live data - present in the mem map file
|
||||
ibt.File, err = winutils.OpenMemMap(IRSDK_MEMMAPFILENAME, fileMapSize)
|
||||
i.File, err = mmaputils.OpenMemMap(MEMMAPFILENAME, fileMapSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to open memory mapped file: %v", err)
|
||||
return fmt.Errorf("failed to open memory mapped file: %+v", err)
|
||||
}
|
||||
|
||||
// To use our windows interface we need to initialize it first
|
||||
// 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
|
||||
ibt.winUtils, err = winutils.Init()
|
||||
i.winUtils, err = mmaputils.Init()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
// I don't believe we need this on windows either, but I'll have to check
|
||||
// We need to open the windows event thing
|
||||
err = ibt.winUtils.OpenWinEvent(IRSDK_DATAVALIDEVENTNAME)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// err = i.winUtils.OpenWinEvent(IRSDK_DATAVALIDEVENTNAME)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
|
||||
// We need to open the broadcast channel
|
||||
err = ibt.winUtils.OpenBroadcastChannel(IRSDK_BROADCASTMSGNAME)
|
||||
// err = i.winUtils.OpenBroadcastChannel(IRSDK_BROADCASTMSGNAME)
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
case IBTFile:
|
||||
i.File, err = os.Open(i.Opts.SourcePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return fmt.Errorf("failed to open file `%s`: %+v", i.Opts.SourcePath, err)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("a source type must be specified")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *IBT) openExporter() error {
|
||||
var err error
|
||||
|
||||
switch i.Opts.IBTExportType {
|
||||
case SharedMemoryFile:
|
||||
// Lets create a shared memory file!
|
||||
shm, err := sharedMem.Create(MEMMAPFILENAME, fileMapSize)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to create memory map file: %+v", err)
|
||||
}
|
||||
|
||||
i.IBTExporter = shm
|
||||
case IBTFile:
|
||||
i.IBTExporter, err = os.OpenFile(i.Opts.IBTExportPath, os.O_CREATE|os.O_RDWR, 0o644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open ibt export file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Init serves to initialize and get a hold of a IBT struct
|
||||
// Receives an Options struct with the required configurations
|
||||
func Init(opts Options) (*IBT, error) {
|
||||
// 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
|
||||
var headerRaw [FileHeaderSize]byte
|
||||
_, err = ibt.File.ReadAt(headerRaw[:], 0)
|
||||
err = ibt.readHeader()
|
||||
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)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Read the disk sub headers
|
||||
var subheaderRaw [SubHeaderSize]byte
|
||||
_, err = ibt.File.ReadAt(subheaderRaw[:], 112)
|
||||
err = ibt.readSubheader()
|
||||
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)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Read session info string
|
||||
sessionInfoStringRaw := make([]byte, ibt.Headers.SessionInfoLength)
|
||||
_, err = ibt.File.ReadAt(sessionInfoStringRaw, int64(ibt.Headers.SessionInfoOffset))
|
||||
err = ibt.readSessionInfo()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to read sessionInfoString from file: %v", err)
|
||||
}
|
||||
ibt.SessionInfo, err = parseSessionInfo(sessionInfoStringRaw, ibt.Headers.SessionInfoLength)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Unable to parse SessionInfoString from file: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Read the telemetry vars info
|
||||
@@ -144,6 +232,7 @@ func Init(f Reader) (*IBT, error) {
|
||||
return &ibt, nil
|
||||
}
|
||||
|
||||
// Close cleans up our irsdk instance
|
||||
func (i *IBT) Close() {
|
||||
if i.winUtils != nil {
|
||||
// If its not live data, the user is the one with ownership of the handle
|
||||
@@ -151,69 +240,3 @@ func (i *IBT) Close() {
|
||||
i.winUtils.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
// if err != nil {
|
||||
// log.Fatalf("Failed to create irsdk instance: %v", err)
|
||||
// }
|
||||
// // fmt.Printf("%s\n", ibt.Headers.ToString())
|
||||
// // fmt.Printf("%s\n", ibt.SubHeaders.ToString())
|
||||
// // fmt.Printf("%s\n", ibt.SessionInfo.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, err := ibt.Update(100 * time.Millisecond)
|
||||
// if res == Unknown {
|
||||
// log.Fatalf("Some unknown error occurred: %v\n", err)
|
||||
// }
|
||||
//
|
||||
// if res == Paused {
|
||||
// fmt.Printf("\r \r")
|
||||
// fmt.Println("GAME IS PAUSED")
|
||||
// continue
|
||||
// }
|
||||
//
|
||||
// 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.Vars.Tick/60, conv.MsToKph(val.Value.(float32)))
|
||||
// } else {
|
||||
// fmt.Printf("\r%d %s", ibt.Vars.Tick/60, "KEY DOESN'T EXIST")
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if res == Ended {
|
||||
// fmt.Println("\nEnd of file found...")
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// fmt.Printf("%d\n", ibt.Vars.Tick)
|
||||
//
|
||||
// ibt.Close()
|
||||
// }
|
||||
|
||||
+101
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
// is interface some windows stuff that we need for the:
|
||||
// - Broadcast Channel
|
||||
// - Valid Data Event windows thing
|
||||
package winutils
|
||||
package mmaputils
|
||||
|
||||
import (
|
||||
"github.com/ESilva15/goirsdk/sharedMem"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
@@ -32,23 +31,12 @@ func (u *IRacingWinUtils) Close() {
|
||||
u.Utils.Close()
|
||||
}
|
||||
|
||||
// OpenMemMap returns a Reader interface that can be used to read the data
|
||||
// No need to encapsulate it
|
||||
func OpenMemMap(path string, size uint32) (Reader, error) {
|
||||
file, err := sharedMem.Open(path, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// OpenWinEvent will open the named windows event
|
||||
func (u *IRacingWinUtils) OpenWinEvent(name string) error {
|
||||
return u.Utils.OpenEvent(name)
|
||||
}
|
||||
|
||||
// OpenWinEvent will open the broadcast channel
|
||||
// OpenBroadcastChannel will open the broadcast channel
|
||||
func (u *IRacingWinUtils) OpenBroadcastChannel(name string) error {
|
||||
return u.Utils.OpenBroadcastChannel(name)
|
||||
}
|
||||
@@ -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
|
||||
// }
|
||||
@@ -1,13 +1,13 @@
|
||||
//go:build windows && cgo
|
||||
// +build windows,cgo
|
||||
// go:build windows
|
||||
|
||||
package winutils
|
||||
package mmaputils
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ESilva15/goirsdk/sharedMem"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
@@ -16,13 +16,11 @@ const (
|
||||
WAIT_TIMEOUT = 258
|
||||
)
|
||||
|
||||
var (
|
||||
once sync.Once
|
||||
)
|
||||
var once sync.Once
|
||||
|
||||
type utils struct {
|
||||
user32DLL *windows.LazyDLL
|
||||
wEvent *windows.Handle
|
||||
wEvent windows.Handle
|
||||
wBroadcastChn uintptr
|
||||
}
|
||||
|
||||
@@ -34,11 +32,22 @@ func newUtils() (*utils, error) {
|
||||
}
|
||||
|
||||
func (u *utils) Close() {
|
||||
closeEvent(u.wEvent)
|
||||
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)
|
||||
@@ -50,7 +59,7 @@ func (u *utils) OpenEvent(eventName string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.wEvent = &event
|
||||
u.wEvent = event
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -90,7 +99,7 @@ func (u *utils) CheckValidDataEvent(timeout time.Duration) bool {
|
||||
t0 := time.Now().UnixNano()
|
||||
timeoutInt := uint32(timeout / time.Millisecond)
|
||||
|
||||
result, err := windows.WaitForSingleObject(*u.wEvent, timeoutInt)
|
||||
result, err := windows.WaitForSingleObject(u.wEvent, timeoutInt)
|
||||
if err != nil {
|
||||
remaining := timeoutInt - uint32((time.Now().UnixNano()-t0)/1000000)
|
||||
if remaining > 0 {
|
||||
@@ -2,9 +2,12 @@ package goirsdk
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/ESilva15/goirsdk/logger"
|
||||
|
||||
"golang.org/x/text/encoding/charmap"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
@@ -307,6 +310,40 @@ type Driver struct {
|
||||
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) {
|
||||
|
||||
+204
-20
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -39,11 +40,13 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
type IRacingState int
|
||||
type VarType struct {
|
||||
Size int // Size is the var type size in bytes
|
||||
Name string // Name is the irsdk var name
|
||||
}
|
||||
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
|
||||
@@ -71,6 +74,20 @@ type Var struct {
|
||||
Value interface{}
|
||||
}
|
||||
|
||||
func (v *Var) ToString() string {
|
||||
return fmt.Sprintf(
|
||||
"Type: %5d (0x%08x)\n"+
|
||||
"Offset: %5d (0x%08x)\n"+
|
||||
"Count: %5d (0x%08x)\n"+
|
||||
"CountAsTime: %5t\n"+
|
||||
"Name: %s\n"+
|
||||
"Description: %s\n"+
|
||||
"Unit: %s",
|
||||
v.Type, v.Type, v.Offset, v.Offset, v.Count, v.Count,
|
||||
v.CountAsTime, v.Name, v.Description, v.Unit,
|
||||
)
|
||||
}
|
||||
|
||||
func (v *IBTVar) ToString() string {
|
||||
return fmt.Sprintf(
|
||||
"Type: %5d (0x%08x)\n"+
|
||||
@@ -91,8 +108,10 @@ type varBuffer struct {
|
||||
}
|
||||
|
||||
type TelemetryVars struct {
|
||||
Tick int32
|
||||
Vars map[string]Var
|
||||
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 {
|
||||
@@ -107,6 +126,14 @@ func (i *IBT) readVariablerHeaders() error {
|
||||
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 {
|
||||
@@ -130,6 +157,38 @@ func (i *IBT) readVariablerHeaders() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *IBT) parseEngineWarnings() {
|
||||
val, ok := i.Vars.Vars["EngineWarnings"]
|
||||
if !ok {
|
||||
log.Fatal("no engine warnings")
|
||||
}
|
||||
|
||||
bitfield, err := strconv.ParseInt(val.Value.(string), 0, 64)
|
||||
if err != nil {
|
||||
log.Fatal("Unable to get engine warnings: " + err.Error())
|
||||
}
|
||||
|
||||
for _, ew := range irsdkEngineWarnings {
|
||||
result := (int(bitfield) & ew.Value) != 0
|
||||
i.Vars.Vars[ew.Name] = Var{Value: result}
|
||||
}
|
||||
}
|
||||
|
||||
// parseBitfieldVariables will parse the variables:
|
||||
// - irsdk_CameraState "CamCameraState"
|
||||
// - irsdk_EngineWarnings "EngineWarnings"
|
||||
// - irsdk_PitSvFlags "PitSvFlags"
|
||||
// - irsdk_Flags "SessionFlags"
|
||||
// - irsdk_SessionState "SessionState"
|
||||
// - irsdk_TrkLoc "CarIdxTrackSurface"
|
||||
//
|
||||
// The approach for now will be to create unique entries in the data map for
|
||||
// the fields in these variables
|
||||
func (i *IBT) parseBitfieldVariables() {
|
||||
// Parse the EngineWarnings variables - its the only one for now
|
||||
i.parseEngineWarnings()
|
||||
}
|
||||
|
||||
func (i *IBT) readData(buf []byte) error {
|
||||
for k, v := range i.Vars.Vars {
|
||||
// Slice of the variable value in the buffer
|
||||
@@ -138,27 +197,119 @@ func (i *IBT) readData(buf []byte) error {
|
||||
// Read the value
|
||||
switch v.Type {
|
||||
case IRSDK_char:
|
||||
v.Value = string(rbuf[0])
|
||||
if v.Count > 1 {
|
||||
// Array of data
|
||||
data := make([]string, v.Count)
|
||||
for entry := 0; entry < int(v.Count); entry++ {
|
||||
entryOffset := v.Offset + int32(entry)*int32(VarTypes[int(v.Type)].Size)
|
||||
rbuf := buf[entryOffset : entryOffset+int32(VarTypes[int(v.Type)].Size)]
|
||||
|
||||
newValue := string(rbuf[0])
|
||||
data[entry] = newValue
|
||||
}
|
||||
|
||||
v.Value = data
|
||||
} else {
|
||||
// Single value
|
||||
v.Value = string(rbuf[0])
|
||||
}
|
||||
case IRSDK_bool:
|
||||
v.Value = int(rbuf[0]) > 0
|
||||
if v.Count > 1 {
|
||||
// Array of data
|
||||
data := make([]bool, v.Count)
|
||||
for entry := 0; entry < int(v.Count); entry++ {
|
||||
entryOffset := v.Offset + int32(entry)*int32(VarTypes[int(v.Type)].Size)
|
||||
rbuf := buf[entryOffset : entryOffset+int32(VarTypes[int(v.Type)].Size)]
|
||||
|
||||
newValue := int(rbuf[0]) > 0
|
||||
data[entry] = newValue
|
||||
}
|
||||
|
||||
v.Value = data
|
||||
} else {
|
||||
// Single value
|
||||
v.Value = int(rbuf[0]) > 0
|
||||
}
|
||||
case IRSDK_int:
|
||||
v.Value = int(binary.LittleEndian.Uint32(rbuf))
|
||||
if v.Count > 1 {
|
||||
// Array of data
|
||||
data := make([]int32, v.Count)
|
||||
for entry := 0; entry < int(v.Count); entry++ {
|
||||
entryOffset := v.Offset + int32(entry)*int32(VarTypes[int(v.Type)].Size)
|
||||
rbuf := buf[entryOffset : entryOffset+int32(VarTypes[int(v.Type)].Size)]
|
||||
newValue := int32(binary.LittleEndian.Uint32(rbuf))
|
||||
data[entry] = newValue
|
||||
}
|
||||
|
||||
v.Value = data
|
||||
} else {
|
||||
// Single value
|
||||
v.Value = int(binary.LittleEndian.Uint32(rbuf))
|
||||
}
|
||||
case IRSDK_bitField:
|
||||
v.Value = fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
|
||||
if v.Count > 1 {
|
||||
// Array of data
|
||||
data := make([]string, v.Count)
|
||||
for entry := 0; entry < int(v.Count); entry++ {
|
||||
entryOffset := v.Offset + int32(entry)*int32(VarTypes[int(v.Type)].Size)
|
||||
rbuf := buf[entryOffset : entryOffset+int32(VarTypes[int(v.Type)].Size)]
|
||||
newValue := fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
|
||||
data[entry] = newValue
|
||||
}
|
||||
|
||||
v.Value = data
|
||||
} else {
|
||||
// Single value
|
||||
v.Value = fmt.Sprintf("0x%x", int(binary.LittleEndian.Uint32(rbuf)))
|
||||
}
|
||||
case IRSDK_float:
|
||||
v.Value = math.Float32frombits(uint32(binary.LittleEndian.Uint32(rbuf)))
|
||||
if v.Count > 1 {
|
||||
// Array of data
|
||||
data := make([]float32, v.Count)
|
||||
for entry := 0; entry < int(v.Count); entry++ {
|
||||
entryOffset := v.Offset + int32(entry)*int32(VarTypes[int(v.Type)].Size)
|
||||
rbuf := buf[entryOffset : entryOffset+int32(VarTypes[int(v.Type)].Size)]
|
||||
newValue := math.Float32frombits(uint32(binary.LittleEndian.Uint32(rbuf)))
|
||||
data[entry] = newValue
|
||||
}
|
||||
|
||||
v.Value = data
|
||||
} else {
|
||||
// Single value
|
||||
v.Value = math.Float32frombits(uint32(binary.LittleEndian.Uint32(rbuf)))
|
||||
}
|
||||
case IRSDK_double:
|
||||
v.Value = math.Float64frombits(uint64(binary.LittleEndian.Uint64(rbuf)))
|
||||
if v.Count > 1 {
|
||||
// Array of data
|
||||
data := make([]float64, v.Count)
|
||||
for entry := 0; entry < int(v.Count); entry++ {
|
||||
entryOffset := v.Offset + int32(entry)*int32(VarTypes[int(v.Type)].Size)
|
||||
rbuf := buf[entryOffset : entryOffset+int32(VarTypes[int(v.Type)].Size)]
|
||||
newValue := math.Float64frombits(uint64(binary.LittleEndian.Uint64(rbuf)))
|
||||
data[entry] = newValue
|
||||
}
|
||||
|
||||
v.Value = data
|
||||
} else {
|
||||
// Single value
|
||||
v.Value = math.Float64frombits(uint64(binary.LittleEndian.Uint64(rbuf)))
|
||||
}
|
||||
}
|
||||
// --------------
|
||||
|
||||
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")
|
||||
@@ -197,6 +348,22 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
|
||||
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
|
||||
@@ -205,11 +372,34 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
|
||||
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 will get the dataframe corresponding to a give tick
|
||||
// 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
|
||||
}
|
||||
@@ -226,11 +416,5 @@ func (i *IBT) Update(timeout time.Duration) (IRacingState, error) {
|
||||
i.Vars.Tick++
|
||||
}
|
||||
|
||||
// Make this happen in a different thread, or have this send to a queue that has a thread
|
||||
// writing to a file
|
||||
if i.FileToExport != "" {
|
||||
i.ExportToIBT(i.FileToExport)
|
||||
}
|
||||
|
||||
return Running, nil
|
||||
}
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
//go:build (linux && cgo) || (darwin && cgo)
|
||||
// +build linux,cgo darwin,cgo
|
||||
|
||||
package winutils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
WAIT_OBJECT_0 = 0
|
||||
WAIT_TIMEOUT = 258
|
||||
)
|
||||
|
||||
var (
|
||||
once sync.Once
|
||||
ErrUnsupportedOS = errors.New("not found")
|
||||
)
|
||||
|
||||
type utils struct {
|
||||
}
|
||||
|
||||
// INITIALIZATION
|
||||
func newUtils() (*utils, error) {
|
||||
return nil, ErrUnsupportedOS
|
||||
}
|
||||
|
||||
func (u *utils) Close() {
|
||||
}
|
||||
|
||||
// openEvent opens a windows.Handle for a given event
|
||||
func (u *utils) OpenEvent(eventName string) error {
|
||||
return ErrUnsupportedOS
|
||||
}
|
||||
|
||||
// OpenBroadcastChannel opens up a broadcast channel to send commands to iracing
|
||||
func (u *utils) OpenBroadcastChannel(name string) error {
|
||||
return ErrUnsupportedOS
|
||||
}
|
||||
|
||||
// INITIALIZATION
|
||||
|
||||
// openEvent waits for a good response for some given time
|
||||
func (u *utils) CheckValidDataEvent(timeout time.Duration) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// SendBroadcastMessage sends a message trough the broadcast channel
|
||||
func (u *utils) SendBroadcastMessage(id, p1, p2 uintptr) error {
|
||||
return ErrUnsupportedOS
|
||||
}
|
||||
Reference in New Issue
Block a user