Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
174b27004f | ||
|
|
a2e14ba6a9 | ||
|
|
a6683df10b | ||
|
|
2d4875fbd0 | ||
|
|
0a8f34423c | ||
|
|
bd10d6b4d6 | ||
|
|
c888dc5436 | ||
|
|
dda300ce6b | ||
|
|
1ac4ab1865 | ||
|
|
a6ab64117c | ||
|
|
1321977f18 | ||
|
|
ffc03e9e49 | ||
|
|
15b997c22f | ||
|
|
59fa825da1 | ||
|
|
dbd4086bf9 | ||
|
|
c1366b010f | ||
|
|
d6362eeeb5 | ||
|
|
1b9a5173b6 | ||
|
|
7675c7e34a | ||
|
|
922c2df88d | ||
|
|
6b09eb5be0 | ||
|
|
1d022a4fa8 | ||
|
|
a251f45859 | ||
|
|
afc4b794bb | ||
|
|
66012b6904 | ||
|
|
a807eb3782 | ||
|
|
fe86993c6d | ||
|
|
5ae0542149 | ||
|
|
4088e4d8f8 | ||
|
|
ce7aabfa09 | ||
|
|
ca57cbd9f0 | ||
|
|
0887fbfd75 | ||
|
|
94ba0e2539 | ||
|
|
c431c389e3 | ||
|
|
16e6a336b0 | ||
|
|
8def8cac68 | ||
|
|
4e91edc036 | ||
|
|
abc60a81d3 | ||
|
|
20dbf15adf | ||
|
|
6dd4db0358 | ||
|
|
2ae29af199 | ||
|
|
5b77b5b941 | ||
|
|
9c7c6d528f | ||
|
|
2146dc8396 | ||
|
|
a28f996330 | ||
|
|
1614675e9d | ||
|
|
0f3a6ceeba | ||
|
|
aa3fa88044 | ||
|
|
5d8552e9a2 | ||
|
|
ac187c9292 | ||
|
|
f2e49f1ba0 | ||
|
|
a980640e40 | ||
|
|
3e92467beb | ||
|
|
74d57a6ece | ||
|
|
24fea285c3 | ||
|
|
d3c4464aa0 | ||
|
|
99a4f794c5 |
@@ -0,0 +1 @@
|
||||
# Peripheral Discovery
|
||||
@@ -0,0 +1,31 @@
|
||||
# Provider Discovery
|
||||
```
|
||||
NewControlPanel()
|
||||
↓
|
||||
go telemService.FindProvider() - has a callback for onFind
|
||||
|
|
||||
|iterates over the known providers
|
||||
|
|
||||
onFind
|
||||
↓
|
||||
telemService.SwitchProvider() - activates the found provider
|
||||
|
|
||||
|-→ Create a background job while the stream hasn't initiated to listened
|
||||
| for data, otherwise the connection might die before we start streaming
|
||||
| ↓
|
||||
| go telemService.ProviderMonitor()
|
||||
↓ | |
|
||||
/-→waits--\ if the provider stops we this healthcheck is stopped
|
||||
\_________/ we clear the provider and once the stream starts
|
||||
go back to the
|
||||
↓
|
||||
FindProvider()
|
||||
```
|
||||
The provider discovery routine starts on `tui/tui.go`.
|
||||
`FindProvider` is called here and it starts a background job.
|
||||
On successful discovery the background job calls the `SwitchProvider` method
|
||||
and dies.
|
||||
|
||||
## Provider stalls
|
||||
A provider stalls once there is no new data.
|
||||
After stalling
|
||||
@@ -0,0 +1 @@
|
||||
# Streaming Flow
|
||||
@@ -21,27 +21,57 @@ or to view the live data:
|
||||
Games implemented so far:
|
||||
- [iRacing](https://www.iracing.com/) using the [goirsdk](https://github.com/ESilva15/goirsdk)
|
||||
|
||||
Games being implemented:
|
||||
- [BeamNG.drive](https://www.beamng.com/game/) using the [gobngsdk](https://github.com/ESilva15/gobngsdk)
|
||||
|
||||
Games to be implemented:
|
||||
- [Assetto Corsa](https://assettocorsa.gg/)
|
||||
<!-- Games being implemented: -->
|
||||
<!-- - [BeamNG.drive](https://www.beamng.com/game/) using the [gobngsdk](https://github.com/ESilva15/gobngsdk) -->
|
||||
<!---->
|
||||
<!-- Games to be implemented: -->
|
||||
<!-- - [Assetto Corsa](https://assettocorsa.gg/) -->
|
||||
|
||||
|
||||
## Roadmap
|
||||
- [ ] Implement the interface for a data source
|
||||
- [ ] Finish implementing BeamNG
|
||||
- [X] Implement the interface for a data source
|
||||
- [ ] Configuration of the peripherals via ESDI
|
||||
- [ ] Detection of the display
|
||||
- [ ] Fuel Calculator
|
||||
- [ ] LapTime Calculator
|
||||
- [ ] A very long list useful stuff like flags, position, more info about
|
||||
other drivers, track conditions and so on so forth
|
||||
- [ ] Dynamic data packets
|
||||
- [ ] More roadmap entries
|
||||
- [ ] Telemetry analysis tool
|
||||
- [ ] Better user interface
|
||||
|
||||
### Shameless begging
|
||||
|
||||
## Development
|
||||
### Mockservers
|
||||
To mock [BeamNG.drive](https://www.beamng.com/game/), I built
|
||||
[BeaMNGMockOg](https://github.com/ESilva15/BeamNGMockOg) (should have though longer
|
||||
about the name).
|
||||
You create a recording by launching the BeamNG and then launching the mockserver with:
|
||||
`BeamNGMockOg record -a 127.0.0.1 -p 4443 -o output.bin`.
|
||||
|
||||
To replay the recording:
|
||||
`BeamNGMockOg replay [--loop] -a 127.0.0.1 -p 4443 -i input.bin`
|
||||
|
||||
### Troubleshooting
|
||||
#### Can't see BeamNG data coming through
|
||||
Use, for example, `tcpdump -i any udp port <port> -X` to check if any data is available.
|
||||
|
||||
|
||||
### Debugging
|
||||
#### Freezes:
|
||||
Using delve:
|
||||
- Launch Terminal1 with `dlv debug . --headless --listen=:2345 -- tui`
|
||||
- Launch Terminal2 and connect to with with `dlv connect :2345`
|
||||
- Type `continue` onto Terminal2 and go to Terminal1 to use the application
|
||||
normally until it hangs.
|
||||
- Go back to Terminal2 to and do a `Ctrl+c` to capture the state and then check
|
||||
what went wrong by looking at the `goroutines` for example.
|
||||
|
||||
pprof:
|
||||
- `go tool pprof http://localhost:8001/debug/pprof/mutex`
|
||||
- type `top` to view the summary
|
||||
- type `web` to view a graph version
|
||||
|
||||
|
||||
## Shameless begging
|
||||
Hey, doesn't hurt to try, its free either way:
|
||||
[Buy me a coffee!](buymeacoffee.com/ESilva_15)
|
||||
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
package cdashdisplay
|
||||
|
||||
// In this file we will place all structs that are 1:1 representation of the
|
||||
// types in the device transport layer ->
|
||||
|
||||
const (
|
||||
ShowIDFalse uint8 = 0
|
||||
ShowIDTrue uint8 = 1
|
||||
)
|
||||
|
||||
const (
|
||||
WinTypeBASE uint8 = iota
|
||||
WinTypeBAR
|
||||
WinTypeSTRING
|
||||
WinTypeTABLE
|
||||
)
|
||||
|
||||
var WinTYPES = []string{"BASE", "BAR", "STRING", "TABLE"}
|
||||
|
||||
type UIDimensions struct {
|
||||
X0 uint16 `yaml:"X0"`
|
||||
Y0 uint16 `yaml:"Y0"`
|
||||
Width uint16 `yaml:"Width"`
|
||||
Height uint16 `yaml:"Height"`
|
||||
}
|
||||
|
||||
type UIDecorations struct {
|
||||
BGColour uint16 `yaml:"BGColour"`
|
||||
FGColour uint16 `yaml:"FGColour"`
|
||||
TitleColour uint16 `yaml:"TitleColour"`
|
||||
BorderColour uint16 `yaml:"BorderColour"`
|
||||
TitleSize uint8 `yaml:"TitleSize"`
|
||||
TextSize uint8 `yaml:"TextSize"`
|
||||
HasBorder uint8 `yaml:"HasBorder"`
|
||||
Padding uint8 `yaml:"Padding"`
|
||||
}
|
||||
|
||||
// NOTE: we can't use FString32 for this - too many bytes
|
||||
// NOTE: use a bit flags for this options instead
|
||||
type UIWindowOpts struct {
|
||||
ShowID uint8 `yaml:"ShowID"`
|
||||
WinType uint8 `yaml:"WinType"`
|
||||
PreviewValue FString32 `yaml:"PreviewValue"`
|
||||
}
|
||||
|
||||
type UIWindow struct {
|
||||
Dims UIDimensions `yaml:"Dims"`
|
||||
Decor UIDecorations `yaml:"Decor"`
|
||||
Opts UIWindowOpts `yaml:"Opts"`
|
||||
Title FString32 `yaml:"Title"`
|
||||
}
|
||||
|
||||
type DesktopUIWindow struct {
|
||||
UIWindow
|
||||
UIData DesktopUIData
|
||||
}
|
||||
|
||||
type DesktopUIData struct {
|
||||
IDX int16 `yaml:"WID"`
|
||||
TelemetryField string `yaml:"TelemetryField"`
|
||||
}
|
||||
|
||||
type UIWindowUpdatePacket struct {
|
||||
WinID int16
|
||||
Window UIWindow
|
||||
}
|
||||
|
||||
// func getUIWindowDTO(w *DesktopWindowData) *UIWindow {
|
||||
//
|
||||
// }
|
||||
+1
-6
@@ -2,8 +2,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -20,10 +18,7 @@ type loggerKey struct{}
|
||||
|
||||
// Execute adds all child commands to the root command and sets flags appropriately.
|
||||
// This is called by main.main(). It only needs to happen once to the rootCmd.
|
||||
func Execute(log *slog.Logger) {
|
||||
ctx := context.WithValue(context.Background(), loggerKey{}, log)
|
||||
rootCmd.SetContext(ctx)
|
||||
|
||||
func Execute() {
|
||||
err := rootCmd.Execute()
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"esdi/logger"
|
||||
esdi "esdi/oldEsdi"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func liveTelemetryCmdAction(cmd *cobra.Command, args []string) {
|
||||
log := logger.GetInstance()
|
||||
|
||||
ddPort, _ := cmd.Flags().GetString("port")
|
||||
outputFile, _ := cmd.Flags().GetString("out")
|
||||
sessionFile, _ := cmd.Flags().GetString("session")
|
||||
|
||||
log.Printf("Called `live`:\nPort: '%s'\nOutFile: '%s'\n", ddPort, outputFile)
|
||||
// log.Printf("Called `live`:\nPort: '%s'\nOutFile: '%s'\n", ddPort, outputFile)
|
||||
|
||||
esdi.RunLiveTelemetry(ddPort, outputFile, sessionFile)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"esdi/logger"
|
||||
esdi "esdi/oldEsdi"
|
||||
|
||||
// "github.com/ESilva15/goirsdk"
|
||||
@@ -10,14 +9,14 @@ import (
|
||||
)
|
||||
|
||||
func offlineTelemetryCmdAction(cmd *cobra.Command, args []string) {
|
||||
log := logger.GetInstance()
|
||||
// log := logger.GetInstance()
|
||||
|
||||
ddPort, _ := cmd.Flags().GetString("port")
|
||||
inFile, _ := cmd.Flags().GetString("in")
|
||||
outFile, _ := cmd.Flags().GetString("out")
|
||||
sessionFile, _ := cmd.Flags().GetString("session")
|
||||
|
||||
log.Printf("Called `offline`:\nPort: '%s'\nSource: '%s'\nOutFile: '%s'\n", ddPort, inFile, outFile)
|
||||
// log.Printf("Called `offline`:\nPort: '%s'\nSource: '%s'\nOutFile: '%s'\n", ddPort, inFile, outFile)
|
||||
|
||||
esdi.RunOfflineTelemetry(ddPort, inFile, outFile, sessionFile)
|
||||
}
|
||||
|
||||
+3
-8
@@ -1,21 +1,16 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"esdi/tui"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"esdi/tui"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func tuiCmdAction(cmd *cobra.Command, args []string) {
|
||||
logger, ok := cmd.Context().Value(loggerKey{}).(*slog.Logger)
|
||||
if !ok {
|
||||
fmt.Printf("Error loading logger from context: %s\n", logger)
|
||||
return
|
||||
}
|
||||
|
||||
err := tui.Run(logger)
|
||||
err := tui.Run(slog.Default())
|
||||
if err != nil {
|
||||
fmt.Printf("Error running TUI: %s\n", err.Error())
|
||||
return
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// Package config is responsible for the configuration of the application
|
||||
package config
|
||||
|
||||
// NOTE: actually make a package out of this if possible - lets try
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
var instance *ESDICfg
|
||||
|
||||
type ESDICfg struct {
|
||||
DefaultSim string `yaml:"default_sim"`
|
||||
DefaultLayout string `yaml:"default_layout"`
|
||||
MetricsServer bool `yaml:"metrics_server"`
|
||||
}
|
||||
|
||||
func (cfg *ESDICfg) loadConfiguration(path string) error {
|
||||
file, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = yaml.Unmarshal(file, &instance)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Setup(path string) error {
|
||||
instance = &ESDICfg{}
|
||||
|
||||
err := instance.loadConfiguration(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetCfg() *ESDICfg {
|
||||
if instance == nil {
|
||||
panic("configuration instance wasn't initialized")
|
||||
}
|
||||
|
||||
return instance
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
default_sim: "iRacing"
|
||||
default_layout: "layout.yaml"
|
||||
metrics_server: true
|
||||
@@ -1,10 +1,12 @@
|
||||
package cdashdisplay
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"esdi/peripheral/communication"
|
||||
"esdi/peripheral/communication/packets"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/tarm/serial"
|
||||
portp "go.bug.st/serial"
|
||||
@@ -46,11 +48,11 @@ func findDisplayPort() (*communication.WalkieTalkie, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pLogger.Info(fmt.Sprintf("Looking into %v", ports))
|
||||
slog.Info(fmt.Sprintf("Looking into %v", ports))
|
||||
|
||||
var wt *communication.WalkieTalkie
|
||||
for _, port := range ports {
|
||||
pLogger.Info(fmt.Sprintf("Trying port %s", port))
|
||||
slog.Info(fmt.Sprintf("Trying port %s", port))
|
||||
|
||||
wt = &communication.WalkieTalkie{
|
||||
Cfg: &serial.Config{
|
||||
@@ -60,7 +62,7 @@ func findDisplayPort() (*communication.WalkieTalkie, error) {
|
||||
},
|
||||
}
|
||||
|
||||
pLogger.Info(fmt.Sprintf("Started probing port %s", port))
|
||||
slog.Info(fmt.Sprintf("Started probing port %s", port))
|
||||
|
||||
probeResult := make(chan error, 1)
|
||||
|
||||
@@ -76,14 +78,14 @@ func findDisplayPort() (*communication.WalkieTalkie, error) {
|
||||
err = fmt.Errorf("probe completely hung/timed out: %s", port)
|
||||
}
|
||||
|
||||
pLogger.Info(fmt.Sprintf("Finished probing port %s", port))
|
||||
slog.Info(fmt.Sprintf("Finished probing port %s", port))
|
||||
|
||||
if err == nil {
|
||||
pLogger.Info(fmt.Sprintf("Success probing port %s: %+v", port, err))
|
||||
slog.Info(fmt.Sprintf("Success probing port %s: %+v", port, err))
|
||||
break
|
||||
}
|
||||
|
||||
pLogger.Info(fmt.Sprintf("wasn't port %s", port))
|
||||
slog.Info(fmt.Sprintf("wasn't port %s", port))
|
||||
wt = nil
|
||||
}
|
||||
|
||||
@@ -91,6 +93,6 @@ func findDisplayPort() (*communication.WalkieTalkie, error) {
|
||||
return nil, fmt.Errorf("couldn't find cdashdisplay")
|
||||
}
|
||||
|
||||
pLogger.Info(fmt.Sprintf("found cdashdisplay on port: %s", wt.Cfg.Name))
|
||||
slog.Info(fmt.Sprintf("found cdashdisplay on port: %s", wt.Cfg.Name))
|
||||
return wt, nil
|
||||
}
|
||||
@@ -8,8 +8,11 @@ import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
helper "esdi/helpers"
|
||||
"esdi/peripheral"
|
||||
"esdi/peripheral/communication"
|
||||
"esdi/peripheral/communication/packets"
|
||||
"esdi/peripheral/types"
|
||||
@@ -18,12 +21,6 @@ import (
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
var pLogger *slog.Logger
|
||||
|
||||
func SetLogger(l *slog.Logger) {
|
||||
pLogger = l
|
||||
}
|
||||
|
||||
// I have to move this to some kind of configuration place
|
||||
const (
|
||||
layoutsDir = "./layouts/"
|
||||
@@ -111,27 +108,62 @@ func NewCDashState() *CDashState {
|
||||
}
|
||||
|
||||
type CDashDisplay struct {
|
||||
WT *communication.WalkieTalkie
|
||||
State *CDashState
|
||||
WT *communication.WalkieTalkie
|
||||
State *CDashState
|
||||
fieldToWindows map[telemetry.FieldID][]int16
|
||||
bufPool sync.Pool
|
||||
failedSends int
|
||||
FailedSendsConsecutiveLimit int
|
||||
}
|
||||
|
||||
// Connect will try to find and connect to the CDashDisplay
|
||||
func NewCDashDisplay() (*CDashDisplay, error) {
|
||||
// Look for the port
|
||||
p, err := findDisplayPort()
|
||||
if err != nil {
|
||||
pLogger.Info("failed to find cdashdisplay port: %s", err.Error())
|
||||
slog.Info("failed to find cdashdisplay port", "reason", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &CDashDisplay{
|
||||
WT: p,
|
||||
State: NewCDashState(),
|
||||
WT: p,
|
||||
State: NewCDashState(),
|
||||
fieldToWindows: make(map[telemetry.FieldID][]int16),
|
||||
bufPool: sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, 0, telemetry.MaxFields*8)
|
||||
return &b
|
||||
},
|
||||
},
|
||||
failedSends: 0,
|
||||
FailedSendsConsecutiveLimit: 5,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *CDashDisplay) SendCommand() {
|
||||
}
|
||||
|
||||
func (d *CDashDisplay) RegisterFieldMapping(fieldID telemetry.FieldID, winID int16) {
|
||||
d.fieldToWindows[fieldID] = append(d.fieldToWindows[fieldID], winID)
|
||||
}
|
||||
|
||||
func (d *CDashDisplay) UnregisterFieldMapping(winID int16) {
|
||||
for fieldID, windows := range d.fieldToWindows {
|
||||
updated := windows[:0]
|
||||
for _, w := range windows {
|
||||
if w != winID {
|
||||
updated = append(updated, w)
|
||||
}
|
||||
|
||||
if len(updated) == 0 {
|
||||
delete(d.fieldToWindows, fieldID)
|
||||
} else {
|
||||
d.fieldToWindows[fieldID] = updated
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *CDashDisplay) CreateWindow(win *DesktopUIWindow) (*DesktopUIWindow, error) {
|
||||
bytes, err := helper.StructToBytes(win.UIWindow)
|
||||
if err != nil {
|
||||
@@ -147,9 +179,12 @@ func (d *CDashDisplay) CreateWindow(win *DesktopUIWindow) (*DesktopUIWindow, err
|
||||
|
||||
win.UIData.IDX = wID.ID
|
||||
|
||||
pLogger.Info(fmt.Sprintf("Recived ID message: %v", wID))
|
||||
slog.Info(fmt.Sprintf("Recived ID message: %v", wID))
|
||||
|
||||
d.State.Layout.AddWindow(win)
|
||||
if fieldID, ok := telemetry.GetFieldID(win.UIData.TelemetryField); ok {
|
||||
d.RegisterFieldMapping(fieldID, win.UIData.IDX)
|
||||
}
|
||||
|
||||
return win, nil
|
||||
}
|
||||
@@ -175,12 +210,14 @@ func (d *CDashDisplay) UpdateWindow(win *DesktopUIWindow) error {
|
||||
// I get it and update it in the controller
|
||||
// I send the pointer here
|
||||
// -> it should be the same pointer then right?
|
||||
pLogger.Debug(fmt.Sprintf("PreUpdate ID: %p", win))
|
||||
slog.Debug(fmt.Sprintf("PreUpdate ID: %p", win))
|
||||
d.State.Layout.Windows[win.UIData.IDX] = win
|
||||
pLogger.Debug(fmt.Sprintf("PostUpdate ID: %p", win))
|
||||
slog.Debug(fmt.Sprintf("PostUpdate ID: %p", win))
|
||||
// Yeah, same address as suspected
|
||||
// I can't think about it right now. I'll think about that tomorrow
|
||||
|
||||
// TODO: need to update the field mappings here!
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -203,14 +240,15 @@ func (d *CDashDisplay) DestroyWindow(wID int16) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// NODE: add this
|
||||
// NOTE: add this
|
||||
d.UnregisterFieldMapping(wID)
|
||||
d.State.Layout.RemoveWindow(wID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *CDashDisplay) updateWindowDimensions(win *UIWindow, packet UpdateDimsPacket) error {
|
||||
pLogger.Debug(fmt.Sprintf("UPDATE: %v", packet))
|
||||
slog.Debug(fmt.Sprintf("UPDATE: %v", packet))
|
||||
|
||||
bytes, err := helper.StructToBytes(packet)
|
||||
if err != nil {
|
||||
@@ -224,9 +262,9 @@ func (d *CDashDisplay) updateWindowDimensions(win *UIWindow, packet UpdateDimsPa
|
||||
}
|
||||
|
||||
// Nothing bad happened afaik
|
||||
pLogger.Debug(fmt.Sprintf("cur dims: %v", win.Dims))
|
||||
slog.Debug(fmt.Sprintf("cur dims: %v", win.Dims))
|
||||
win.Dims = packet.Dims
|
||||
pLogger.Debug(fmt.Sprintf("new dims: %v", win.Dims))
|
||||
slog.Debug(fmt.Sprintf("new dims: %v", win.Dims))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -298,7 +336,7 @@ func (d *CDashDisplay) ResizeWindow(wID int16, delta *helper.Vector) error {
|
||||
|
||||
func (d *CDashDisplay) SaveLayout(outputPath string) error {
|
||||
file, err := os.OpenFile(path.Join(layoutsDir, outputPath),
|
||||
os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
|
||||
os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -339,12 +377,33 @@ func (d *CDashDisplay) LoadLayout(layoutName string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *CDashDisplay) SendData(data *telemetry.TelemetryData) {
|
||||
packet := data.Pack()
|
||||
func (d *CDashDisplay) UnloadLayout() error {
|
||||
var err error
|
||||
for _, w := range d.State.Layout.Windows {
|
||||
slog.Debug(fmt.Sprintf("= Removing %d ==============================================",
|
||||
w.UIData.IDX))
|
||||
|
||||
err = d.DestroyWindow(w.UIData.IDX)
|
||||
time.Sleep(75 * time.Millisecond)
|
||||
if err != nil {
|
||||
slog.Error(fmt.Sprintf("failed to destroy window: %+v", err))
|
||||
// NOTE: Add a way to handle multiple errors ?
|
||||
return err
|
||||
}
|
||||
|
||||
slog.Debug(fmt.Sprintf("= Removing %d ==============================================",
|
||||
w.UIData.IDX))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *CDashDisplay) SendData(data *telemetry.TelemetryData) error {
|
||||
packet := d.encodePacket(data)
|
||||
|
||||
bytes, err := helper.StructToBytes(packet)
|
||||
if err != nil {
|
||||
return
|
||||
return peripheral.ErrFailureToPackData
|
||||
}
|
||||
|
||||
curStr := ""
|
||||
@@ -354,7 +413,6 @@ func (d *CDashDisplay) SendData(data *telemetry.TelemetryData) {
|
||||
curStr += fmt.Sprintf("%02x ", byte)
|
||||
|
||||
if byteCount == 8 {
|
||||
pLogger.Debug(curStr)
|
||||
curStr = ""
|
||||
byteCount = 0
|
||||
}
|
||||
@@ -363,6 +421,11 @@ func (d *CDashDisplay) SendData(data *telemetry.TelemetryData) {
|
||||
// var ack packets.AckPacket
|
||||
err = d.WT.SendCommand(sendDataCMDID, bytes, nil)
|
||||
if err != nil && err != io.EOF {
|
||||
return
|
||||
if d.failedSends == d.FailedSendsConsecutiveLimit {
|
||||
return peripheral.ErrDeviceTimedOut
|
||||
}
|
||||
d.failedSends++
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cdashdisplay
|
||||
|
||||
import (
|
||||
"esdi/peripheral/devices"
|
||||
"esdi/telemetry"
|
||||
)
|
||||
|
||||
// TODO: I believe we don't need the #esdi/peripheral/devices thing anymore
|
||||
const (
|
||||
ID = devices.CDashDisplayDevID
|
||||
NAME = devices.CDashDisplayDevName
|
||||
)
|
||||
|
||||
func (cds *CDashDisplay) Name() string {
|
||||
return NAME
|
||||
}
|
||||
|
||||
func (cds *CDashDisplay) RequiredFields() []telemetry.FieldID {
|
||||
fields := make([]telemetry.FieldID, 0, len(cds.State.Layout.Windows))
|
||||
|
||||
for _, w := range cds.State.Layout.Windows {
|
||||
if fieldID, ok := telemetry.GetFieldID(w.UIData.TelemetryField); ok {
|
||||
fields = append(fields, fieldID)
|
||||
}
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package cdashdisplay
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
type LayoutTree struct {
|
||||
Windows map[int16]*DesktopUIWindow `yaml:"Windows"`
|
||||
@@ -13,13 +16,13 @@ func NewLayoutTree() *LayoutTree {
|
||||
}
|
||||
|
||||
func (l *LayoutTree) AddWindow(w *DesktopUIWindow) {
|
||||
pLogger.Debug(fmt.Sprintf("adding window '%d' - %v", w.UIData.IDX))
|
||||
slog.Debug(fmt.Sprintf("adding window '%d' - %v", w.UIData.IDX))
|
||||
l.Windows[w.UIData.IDX] = w
|
||||
pLogger.Debug(fmt.Sprintf("new map - %v", l.Windows))
|
||||
slog.Debug(fmt.Sprintf("new map - %v", l.Windows))
|
||||
}
|
||||
|
||||
func (l *LayoutTree) RemoveWindow(idx int16) {
|
||||
pLogger.Debug(fmt.Sprintf("removing window '%d'", idx))
|
||||
slog.Debug(fmt.Sprintf("removing window '%d'", idx))
|
||||
delete(l.Windows, idx)
|
||||
pLogger.Debug(fmt.Sprintf("new map - %v", l.Windows))
|
||||
slog.Debug(fmt.Sprintf("new map - %v", l.Windows))
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package cdashdisplay
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"esdi/telemetry"
|
||||
)
|
||||
|
||||
// In this file we will place all structs that are 1:1 representation of the
|
||||
// types in the device transport layer ->
|
||||
|
||||
const (
|
||||
ShowIDFalse uint8 = 0
|
||||
ShowIDTrue uint8 = 1
|
||||
)
|
||||
|
||||
const (
|
||||
WinTypeBASE uint8 = iota
|
||||
WinTypeBAR
|
||||
WinTypeSTRING
|
||||
WinTypeTABLE
|
||||
)
|
||||
|
||||
var WinTYPES = []string{"BASE", "BAR", "STRING", "TABLE"}
|
||||
|
||||
type UIDimensions struct {
|
||||
X0 uint16 `yaml:"X0"`
|
||||
Y0 uint16 `yaml:"Y0"`
|
||||
Width uint16 `yaml:"Width"`
|
||||
Height uint16 `yaml:"Height"`
|
||||
}
|
||||
|
||||
type UIDecorations struct {
|
||||
BGColour uint16 `yaml:"BGColour"`
|
||||
FGColour uint16 `yaml:"FGColour"`
|
||||
TitleColour uint16 `yaml:"TitleColour"`
|
||||
BorderColour uint16 `yaml:"BorderColour"`
|
||||
TitleSize uint8 `yaml:"TitleSize"`
|
||||
TextSize uint8 `yaml:"TextSize"`
|
||||
HasBorder uint8 `yaml:"HasBorder"`
|
||||
Padding uint8 `yaml:"Padding"`
|
||||
}
|
||||
|
||||
// NOTE: we can't use FString32 for this - too many bytes
|
||||
// NOTE: use a bit flags for this options instead
|
||||
type UIWindowOpts struct {
|
||||
ShowID uint8 `yaml:"ShowID"`
|
||||
WinType uint8 `yaml:"WinType"`
|
||||
PreviewValue FString32 `yaml:"PreviewValue"`
|
||||
}
|
||||
|
||||
type UIWindow struct {
|
||||
Dims UIDimensions `yaml:"Dims"`
|
||||
Decor UIDecorations `yaml:"Decor"`
|
||||
Opts UIWindowOpts `yaml:"Opts"`
|
||||
Title FString32 `yaml:"Title"`
|
||||
}
|
||||
|
||||
type DesktopUIWindow struct {
|
||||
UIWindow
|
||||
UIData DesktopUIData
|
||||
}
|
||||
|
||||
type DesktopUIData struct {
|
||||
IDX int16 `yaml:"WID"`
|
||||
TelemetryField string `yaml:"TelemetryField"`
|
||||
}
|
||||
|
||||
type UIWindowUpdatePacket struct {
|
||||
WinID int16
|
||||
Window UIWindow
|
||||
}
|
||||
|
||||
// TODO: this is here because this is the only device I use like this
|
||||
// once I add another serial device I will move this somewhere else that can
|
||||
// be reused by all devices but still is decoupled from the telemetry package
|
||||
func (cds *CDashDisplay) encodePacket(td *telemetry.TelemetryData) []byte {
|
||||
bufPtr := cds.bufPool.Get().(*[]byte)
|
||||
buf := (*bufPtr)[:0]
|
||||
|
||||
for fieldID, windowIDs := range cds.fieldToWindows {
|
||||
if int(fieldID) >= len(td.Values) || len(windowIDs) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
tf := &td.Values[fieldID]
|
||||
|
||||
for _, winID := range windowIDs {
|
||||
buf = packField(winID, tf, buf)
|
||||
}
|
||||
}
|
||||
|
||||
// We have to copy here because we have to return the buffer
|
||||
result := make([]byte, len(buf))
|
||||
copy(result, buf)
|
||||
|
||||
cds.bufPool.Put(&buf)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Pack will pack this current TelemetryField into bytes to send over the wire
|
||||
// Format:
|
||||
// 0x00 - Field ID
|
||||
// 0x00 |
|
||||
// 0x01 - DataType
|
||||
// 0x02 - if its a (u)int8
|
||||
// or
|
||||
// 0x02 - if its a (u)int16 - first byte
|
||||
// 0x02 - if its a (u)int16 - second byte
|
||||
// or
|
||||
// 0x02 - str len max is 255 chars
|
||||
// [0x02] - str
|
||||
func packField(winID int16, tf *telemetry.TelemetryField, dest []byte) []byte {
|
||||
// NOTE: maybe we can have a pool of these so we don't have to create them here
|
||||
// or whatever
|
||||
dest = append(dest, uint8(winID), uint8(winID>>8))
|
||||
dest = append(dest, uint8(tf.Type))
|
||||
|
||||
switch tf.Type {
|
||||
case telemetry.DataTypeINT8, telemetry.DataTypeUINT8, telemetry.DataTypeCHAR:
|
||||
dest = append(dest, uint8(tf.Raw))
|
||||
case telemetry.DataTypeINT16, telemetry.DataTypeUINT16:
|
||||
dest = append(dest, uint8(tf.Raw), uint8(tf.Raw>>8))
|
||||
case telemetry.DataTypeINT32, telemetry.DataTypeUINT32:
|
||||
dest = append(dest, uint8(tf.Raw), uint8(tf.Raw>>8), uint8(tf.Raw>>16), uint8(tf.Raw>>24))
|
||||
case telemetry.DataTypeINT64, telemetry.DataTypeUINT64:
|
||||
dest = append(
|
||||
dest, uint8(tf.Raw), uint8(tf.Raw>>8), uint8(tf.Raw>>16),
|
||||
uint8(tf.Raw>>24), uint8(tf.Raw>>32), uint8(tf.Raw>>40), uint8(tf.Raw>>48),
|
||||
uint8(tf.Raw>>56),
|
||||
)
|
||||
case telemetry.DataTypeSTRING:
|
||||
l := min(len(tf.Str), math.MaxUint8)
|
||||
|
||||
dest = append(dest, uint8(l))
|
||||
dest = append(dest, tf.Str[:l]...)
|
||||
}
|
||||
|
||||
return dest
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Package devices is a peripheral factory
|
||||
package devices
|
||||
|
||||
import (
|
||||
"esdi/devices/cdashdisplay"
|
||||
"esdi/devices/uidevice"
|
||||
"esdi/peripheral"
|
||||
)
|
||||
|
||||
type Device struct {
|
||||
Name string
|
||||
Discover func() (peripheral.Peripheral, error)
|
||||
}
|
||||
|
||||
var List map[string]Device = map[string]Device{
|
||||
uidevice.NAME: {
|
||||
Name: uidevice.NAME,
|
||||
Discover: DiscoverUIDevice,
|
||||
},
|
||||
cdashdisplay.NAME: {
|
||||
Name: cdashdisplay.NAME,
|
||||
Discover: DiscoverCDashDisplay,
|
||||
},
|
||||
}
|
||||
|
||||
func DiscoverUIDevice() (peripheral.Peripheral, error) {
|
||||
uidev, err := uidevice.NewUIDevice()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return uidev, nil
|
||||
}
|
||||
|
||||
func DiscoverCDashDisplay() (peripheral.Peripheral, error) {
|
||||
// Create a cdashdisplay
|
||||
display, err := cdashdisplay.NewCDashDisplay()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return display, nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package uidevice
|
||||
|
||||
import (
|
||||
"esdi/peripheral"
|
||||
"esdi/telemetry"
|
||||
)
|
||||
|
||||
type UIDevice struct {
|
||||
dataChan chan telemetry.TelemetryData
|
||||
}
|
||||
|
||||
const NAME = "UIView"
|
||||
|
||||
func NewUIDevice() (peripheral.Peripheral, error) {
|
||||
return &UIDevice{
|
||||
dataChan: make(chan telemetry.TelemetryData, 1),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (uid *UIDevice) SendData(data *telemetry.TelemetryData) error {
|
||||
if data == nil {
|
||||
return peripheral.ErrInvalidData
|
||||
}
|
||||
|
||||
select {
|
||||
case uid.dataChan <- *data:
|
||||
default:
|
||||
// Drop frame if buffer is full
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uid *UIDevice) Name() string {
|
||||
return NAME
|
||||
}
|
||||
|
||||
func (uid *UIDevice) DataChannel() <-chan telemetry.TelemetryData {
|
||||
return uid.dataChan
|
||||
}
|
||||
|
||||
func (uid *UIDevice) RequiredFields() []telemetry.FieldID {
|
||||
return []telemetry.FieldID{
|
||||
telemetry.Speed,
|
||||
telemetry.Gear,
|
||||
telemetry.RPM,
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
module esdi
|
||||
|
||||
go 1.25.5
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
github.com/ESilva15/ESgoRepl v0.1.0
|
||||
github.com/ESilva15/gobngsdk v0.0.2
|
||||
github.com/ESilva15/goirsdk v0.2.11
|
||||
github.com/ESilva15/gobngsdk v1.1.3
|
||||
github.com/ESilva15/goirsdk v0.3.0
|
||||
github.com/arl/statsviz v0.8.0
|
||||
github.com/gdamore/tcell/v2 v2.8.1
|
||||
github.com/rivo/tview v0.42.0
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
github.com/ESilva15/ESgoRepl v0.1.0 h1:hOVcRBfdP8Yw1kLr2tFoM3SetV7vxFswKjzfAtq8UgM=
|
||||
github.com/ESilva15/ESgoRepl v0.1.0/go.mod h1:O2JQMyEgHy0zf9UvzvLNvp2w95T2uazc3torrzRmG9Y=
|
||||
github.com/ESilva15/gobngsdk v0.0.2 h1:N6stNOE14Wg80BAZMFu/Qd9Qa/J0DmExCfdPoDf7lco=
|
||||
github.com/ESilva15/gobngsdk v0.0.2/go.mod h1:cKLaZRgM0tGGXDvosaSjHnxeyC5Y6rg7zCLqEUJnOzw=
|
||||
github.com/ESilva15/goirsdk v0.2.11 h1:C/HuO9xGmRJ01vMR0KRjrhcMEfq1Mea1rQK0CICaOU4=
|
||||
github.com/ESilva15/goirsdk v0.2.11/go.mod h1:5borQbw+L4fe9b58JFHRHZwrzz0sMVAteuYbRnFOc0Q=
|
||||
github.com/ESilva15/gobngsdk v1.1.3 h1:CFaz2KjHKnBLrQuEN1QHOd1761cWM/rmTwLpSLrgbe4=
|
||||
github.com/ESilva15/gobngsdk v1.1.3/go.mod h1:cKLaZRgM0tGGXDvosaSjHnxeyC5Y6rg7zCLqEUJnOzw=
|
||||
github.com/ESilva15/goirsdk v0.3.0 h1:6D95Avq7chikGHwEUKh7Y/HaLHOWQ75Qxaz8oMDSfrw=
|
||||
github.com/ESilva15/goirsdk v0.3.0/go.mod h1:5borQbw+L4fe9b58JFHRHZwrzz0sMVAteuYbRnFOc0Q=
|
||||
github.com/arl/statsviz v0.8.0 h1:O6GjjVxEDxcByAucOSl29HaGYLXsuwA3ujJw8H9E7/U=
|
||||
github.com/arl/statsviz v0.8.0/go.mod h1:XlrbiT7xYT03xaW9JMMfD8KFUhBOESJwfyNJu83PbB0=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
|
||||
Executable
+337
@@ -0,0 +1,337 @@
|
||||
Windows:
|
||||
1:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 170
|
||||
Y0: 136
|
||||
Width: 40
|
||||
Height: 55
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 4
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: '>'
|
||||
Title: ->
|
||||
uidata:
|
||||
WID: 1
|
||||
TelemetryField: Right Indicator
|
||||
2:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 341
|
||||
Y0: 417
|
||||
Width: 40
|
||||
Height: 55
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 4
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: A
|
||||
Title: ABS
|
||||
uidata:
|
||||
WID: 2
|
||||
TelemetryField: ABS Dash Light
|
||||
3:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 470
|
||||
Y0: 71
|
||||
Width: 322
|
||||
Height: 57
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 4
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: "9999"
|
||||
Title: Dig Tacho
|
||||
uidata:
|
||||
WID: 3
|
||||
TelemetryField: RPM
|
||||
4:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 321
|
||||
Y0: 73
|
||||
Width: 134
|
||||
Height: 111
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 12
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: R
|
||||
Title: Box
|
||||
uidata:
|
||||
WID: 4
|
||||
TelemetryField: Gear
|
||||
5:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 80
|
||||
Y0: 136
|
||||
Width: 40
|
||||
Height: 55
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 4
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: <
|
||||
Title: <-
|
||||
uidata:
|
||||
WID: 5
|
||||
TelemetryField: Left Indicator
|
||||
6:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 694
|
||||
Y0: 367
|
||||
Width: 100
|
||||
Height: 50
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 3
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: "101.4"
|
||||
Title: Oil T
|
||||
uidata:
|
||||
WID: 6
|
||||
TelemetryField: Oil Temperature
|
||||
7:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 386
|
||||
Y0: 417
|
||||
Width: 40
|
||||
Height: 55
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 4
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: T
|
||||
Title: TC
|
||||
uidata:
|
||||
WID: 7
|
||||
TelemetryField: Traction Control Light
|
||||
8:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 431
|
||||
Y0: 417
|
||||
Width: 40
|
||||
Height: 55
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 4
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: B
|
||||
Title: Bat
|
||||
uidata:
|
||||
WID: 8
|
||||
TelemetryField: Battery Light
|
||||
9:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 321
|
||||
Y0: 195
|
||||
Width: 134
|
||||
Height: 80
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 7
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: "234"
|
||||
Title: SPEEDO
|
||||
uidata:
|
||||
WID: 9
|
||||
TelemetryField: Speed
|
||||
10:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 590
|
||||
Y0: 367
|
||||
Width: 100
|
||||
Height: 50
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 3
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: "101.5"
|
||||
Title: Water T
|
||||
uidata:
|
||||
WID: 10
|
||||
TelemetryField: Water Temperature
|
||||
11:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 470
|
||||
Y0: 132
|
||||
Width: 169
|
||||
Height: 50
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 3
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: "123.4"
|
||||
Title: Fuel Level
|
||||
uidata:
|
||||
WID: 11
|
||||
TelemetryField: Fuel Level
|
||||
12:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 694
|
||||
Y0: 423
|
||||
Width: 100
|
||||
Height: 50
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 3
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: "4.56"
|
||||
Title: Oil P
|
||||
uidata:
|
||||
WID: 12
|
||||
TelemetryField: Oil Pressure
|
||||
13:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 296
|
||||
Y0: 417
|
||||
Width: 40
|
||||
Height: 55
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 2
|
||||
TextSize: 4
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 2
|
||||
PreviewValue: P
|
||||
Title: HB
|
||||
uidata:
|
||||
WID: 13
|
||||
TelemetryField: Parking Brake Dash Light
|
||||
14:
|
||||
uiwindow:
|
||||
Dims:
|
||||
X0: 142
|
||||
Y0: 19
|
||||
Width: 500
|
||||
Height: 20
|
||||
Decor:
|
||||
BGColour: 4161
|
||||
FGColour: 65535
|
||||
TitleColour: 65535
|
||||
BorderColour: 63488
|
||||
TitleSize: 1
|
||||
TextSize: 2
|
||||
HasBorder: 1
|
||||
Padding: 0
|
||||
Opts:
|
||||
ShowID: 0
|
||||
WinType: 1
|
||||
PreviewValue: "5678"
|
||||
Title: TACHO
|
||||
uidata:
|
||||
WID: 14
|
||||
TelemetryField: RPM
|
||||
@@ -1,22 +0,0 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var l *log.Logger
|
||||
var once sync.Once
|
||||
|
||||
func createLogger() {
|
||||
l = log.New(os.Stdout, "[esdi] ", log.LstdFlags | log.Lshortfile)
|
||||
}
|
||||
|
||||
func GetInstance() *log.Logger {
|
||||
once.Do(func() {
|
||||
createLogger()
|
||||
})
|
||||
|
||||
return l
|
||||
}
|
||||
@@ -1,39 +1,93 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/pprof"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"esdi/cmd"
|
||||
"esdi/telemetry"
|
||||
"esdi/config"
|
||||
|
||||
"github.com/arl/statsviz"
|
||||
)
|
||||
|
||||
func main() {
|
||||
output, err := os.OpenFile("./output.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0755)
|
||||
// NOTE: in go we have the init() function. Its a function that runs before
|
||||
// everything else in a package. Make use of that
|
||||
|
||||
func initApplication() {
|
||||
fmt.Fprint(os.Stdout, "\x1b]0;ESDI\x07")
|
||||
|
||||
// 1. This is the first initialization setup we do so we can log
|
||||
err := setupLogger()
|
||||
if err != nil {
|
||||
panic("failed to open logging file: " + err.Error())
|
||||
}
|
||||
|
||||
// 2. This is the second thing we setup because we need some stuff to run
|
||||
// other things
|
||||
err = config.Setup("./config/config.yaml")
|
||||
if err != nil {
|
||||
panic("failed to setup config: " + err.Error())
|
||||
}
|
||||
|
||||
// Performance analysis
|
||||
if config.GetCfg().MetricsServer {
|
||||
slog.Info("Setting up metrics server...")
|
||||
err = runStatviz()
|
||||
if err != nil {
|
||||
slog.Error(fmt.Sprintf("failed to setup metrics server: %+v", err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setupLogger() error {
|
||||
output, err := os.OpenFile("./output.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger := slog.New(
|
||||
slog.NewTextHandler(output, &slog.HandlerOptions{
|
||||
Level: slog.LevelDebug,
|
||||
}),
|
||||
)
|
||||
|
||||
// Performance analysis
|
||||
slog.SetDefault(logger)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func runStatviz() error {
|
||||
mux := http.NewServeMux()
|
||||
statsviz.Register(mux)
|
||||
err := statsviz.Register(mux, statsviz.Root("/"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.SetBlockProfileRate(1)
|
||||
runtime.SetMutexProfileFraction(1)
|
||||
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
||||
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
||||
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
||||
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
|
||||
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
|
||||
|
||||
go func() {
|
||||
http.ListenAndServe("localhost:8001", mux)
|
||||
err := http.ListenAndServe("localhost:8001", mux)
|
||||
if err != nil {
|
||||
slog.Error("Failed to set up server for statsviz", "err", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Setting up some internal data structures
|
||||
telemetry.Init()
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
initApplication()
|
||||
|
||||
// Launches the cobra package stuff
|
||||
cmd.Execute(logger)
|
||||
cmd.Execute()
|
||||
}
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ func RunLiveTelemetry(port string, output string, session string) {
|
||||
// log.Fatalf("Failed to create iRacing interface: %v", err)
|
||||
// }
|
||||
|
||||
irsdk, err := goirsdk.Init(nil, output, session)
|
||||
irsdk, err := goirsdk.Init(goirsdk.Options{})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to create irsdk instance: %v\n", err)
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@ import "esdi/peripheral/types"
|
||||
// IDs for our devices. They need to be correctly mapped on the devices
|
||||
// themselves so we can discover them
|
||||
const (
|
||||
CDashDisplayDevID = 0x01
|
||||
ESBtnBoxDevID = 0x02
|
||||
CDashDisplayDevID = 0x01
|
||||
CDashDisplayDevName = "CDashDisplay"
|
||||
ESBtnBoxDevID = 0x02
|
||||
)
|
||||
|
||||
// DeviceMap maps the implemented devices
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package peripheral
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidData = errors.New("invalid data")
|
||||
ErrDeviceTimedOut = errors.New("device timed out")
|
||||
ErrFailureToPackData = errors.New("failed to pack received data")
|
||||
)
|
||||
@@ -2,9 +2,11 @@
|
||||
package peripheral
|
||||
|
||||
import (
|
||||
"esdi/peripheral/devices"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"esdi/peripheral/devices"
|
||||
"esdi/telemetry"
|
||||
)
|
||||
|
||||
type PeripheralType string
|
||||
@@ -13,6 +15,12 @@ const (
|
||||
DisplayPeripheral PeripheralType = "display"
|
||||
)
|
||||
|
||||
type Peripheral interface {
|
||||
Name() string
|
||||
SendData(*telemetry.TelemetryData) error
|
||||
RequiredFields() []telemetry.FieldID
|
||||
}
|
||||
|
||||
type PeripheralDeviceClerk struct {
|
||||
// mu sync.RWMutex
|
||||
Devices map[uint8]*PeripheralDevice
|
||||
|
||||
+208
-21
@@ -1,44 +1,231 @@
|
||||
// Package beamng is the BeamNG.drive data provider
|
||||
package beamng
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/ESilva15/gobngsdk"
|
||||
"esdi/telemetry"
|
||||
|
||||
bngsdk "github.com/ESilva15/gobngsdk"
|
||||
)
|
||||
|
||||
// This will implement the GameSink interface from the main package
|
||||
// BeamNG is the concrete implementation of the TelemetryProvider interface
|
||||
// for BeamNG.drive
|
||||
// NOTE: document this please. What is a TelemetryData????
|
||||
type BeamNG struct {
|
||||
SDK *bngsdk.BNGSDK
|
||||
logger *slog.Logger
|
||||
|
||||
SDK *bngsdk.BeamNGSDK
|
||||
og *bngsdk.Outgauge
|
||||
|
||||
// data handling
|
||||
mut sync.Mutex
|
||||
data *telemetry.TelemetryData
|
||||
updaters [telemetry.MaxFields]func(*telemetry.TelemetryField)
|
||||
|
||||
// stream control
|
||||
wg sync.WaitGroup
|
||||
streamCancel context.CancelFunc
|
||||
|
||||
// timing
|
||||
ticker *time.Ticker
|
||||
}
|
||||
|
||||
const (
|
||||
NAME = "BeamNG.Drive"
|
||||
NAME = "BeamNG.drive"
|
||||
)
|
||||
|
||||
func Init(ip string, port int) (BeamNG, error) {
|
||||
var err error
|
||||
|
||||
sdk, err := bngsdk.Init(ip, port)
|
||||
func NewBeamNGProvider(logger *slog.Logger, opts *bngsdk.Options) (*BeamNG, error) {
|
||||
beam, err := bngsdk.NewBngSDK(*opts)
|
||||
if err != nil {
|
||||
return BeamNG{}, err
|
||||
return &BeamNG{}, err
|
||||
}
|
||||
|
||||
return BeamNG{SDK: &sdk}, nil
|
||||
}
|
||||
|
||||
// GetData will retrieve a given field by its name from the OutGauge data
|
||||
func (b *BeamNG) GetData(fieldName string) (interface{}, error) {
|
||||
if val, ok := b.SDK.DataDict[fieldName]; ok {
|
||||
return val, nil
|
||||
provider := &BeamNG{
|
||||
logger: logger.With("TelemetryProvider", NAME),
|
||||
data: telemetry.NewTelemetryData(),
|
||||
SDK: beam,
|
||||
og: &bngsdk.Outgauge{},
|
||||
ticker: time.NewTicker(time.Second / 60),
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("key `%s` doesn't exist", fieldName)
|
||||
provider.updaters = [telemetry.MaxFields]func(*telemetry.TelemetryField){
|
||||
telemetry.Speed: provider.updateSpeed,
|
||||
telemetry.Gear: provider.updateGear,
|
||||
telemetry.RPM: provider.updateRPM,
|
||||
telemetry.FuelLevel: provider.fuelLevel,
|
||||
// Engine Data
|
||||
telemetry.OilPress: provider.oilPressure,
|
||||
telemetry.OilTemp: provider.oilTemp,
|
||||
telemetry.WaterTemp: provider.engTemp,
|
||||
// Electrics (dash lights and so on)
|
||||
telemetry.PitSpeedLimiter: provider.pitSpeedLimiter,
|
||||
telemetry.LeftIndicator: provider.leftIndicator,
|
||||
telemetry.RightIndicator: provider.rightIndicator,
|
||||
telemetry.Hazards: provider.unused,
|
||||
telemetry.ABSWarningLight: provider.absLight,
|
||||
telemetry.ParkingBrakeLight: provider.handbrakeLight,
|
||||
telemetry.TCLight: provider.tcLight,
|
||||
telemetry.BatteryLight: provider.batteryLight,
|
||||
}
|
||||
|
||||
// Set the unset telemetry fields on the updaters as unused fields
|
||||
for k := range int(telemetry.MaxFields) {
|
||||
if provider.updaters[k] == nil {
|
||||
provider.updaters[k] = provider.unused
|
||||
}
|
||||
}
|
||||
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (b *BeamNG) UpdateData() error {
|
||||
return b.SDK.ReadData()
|
||||
func (b *BeamNG) Close() {
|
||||
b.SDK.Close()
|
||||
}
|
||||
|
||||
func (b *BeamNG) GetSessionInfo() (interface{}, error) {
|
||||
return nil, fmt.Errorf("Not implemented")
|
||||
func (b *BeamNG) Name() string {
|
||||
return NAME
|
||||
}
|
||||
|
||||
func (b *BeamNG) IsAlive(timeout time.Duration) bool {
|
||||
_, err := b.SDK.Update()
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (b *BeamNG) StopStream() {
|
||||
if b.streamCancel == nil {
|
||||
return
|
||||
}
|
||||
|
||||
b.streamCancel()
|
||||
}
|
||||
|
||||
func (b *BeamNG) Stream() (<-chan telemetry.TelemetryData, error) {
|
||||
var ctx context.Context
|
||||
ctx, b.streamCancel = context.WithCancel(context.Background())
|
||||
|
||||
// Start the stream
|
||||
ch := b.stream(ctx)
|
||||
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (b *BeamNG) Subscribe(requestFields []telemetry.FieldID) {
|
||||
// NOTE: document how the Subscribe funtion works
|
||||
slog.Debug(fmt.Sprintf("Len Req: %d\n", len(requestFields)))
|
||||
|
||||
b.data.ActiveBinds = make([]telemetry.BoundField, 0, len(requestFields))
|
||||
|
||||
// First we must add the virtual fields
|
||||
// we will add their dependencies and the primitives to a slice
|
||||
pendingBinds := make([]telemetry.FieldID, telemetry.MaxFields)
|
||||
|
||||
for _, id := range requestFields {
|
||||
switch id {
|
||||
case telemetry.RPMStateColour:
|
||||
b.data.VirtualBinds = append(b.data.VirtualBinds, telemetry.NewRPMLights())
|
||||
case telemetry.FCCurrentLap:
|
||||
b.data.VirtualBinds = append(b.data.VirtualBinds,
|
||||
telemetry.NewFuelCalculator(slog.Default().WithGroup("FUEL CALC")))
|
||||
default:
|
||||
// primitive telemetry field
|
||||
pendingBinds = append(pendingBinds, id)
|
||||
}
|
||||
}
|
||||
|
||||
boundCheck := make(map[telemetry.FieldID]bool)
|
||||
|
||||
// Now that we know all the fields we need to bind we follow the binding procedure
|
||||
for _, id := range pendingBinds {
|
||||
// Check if we already bound this FieldID
|
||||
if boundCheck[id] {
|
||||
continue
|
||||
}
|
||||
|
||||
binding := telemetry.BoundField{
|
||||
ID: id,
|
||||
}
|
||||
|
||||
b.data.ActiveBinds = append(b.data.ActiveBinds, binding)
|
||||
boundCheck[id] = true
|
||||
}
|
||||
|
||||
slog.Debug(fmt.Sprintf("Subscribed: %+v\n", b.data.ActiveBinds))
|
||||
}
|
||||
|
||||
// Internal
|
||||
|
||||
func (b *BeamNG) readData() {
|
||||
slog.Debug("READING THIS DATA")
|
||||
ogSnapshot, err := b.SDK.Update()
|
||||
slog.Debug("THE DATA WAS READ")
|
||||
if err != nil {
|
||||
slog.Error("Error getting data", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
b.mut.Lock()
|
||||
b.og = ogSnapshot
|
||||
defer b.mut.Unlock()
|
||||
|
||||
// Read 1 to 1 data
|
||||
slog.Debug("Reading normal data binds")
|
||||
for _, bind := range b.data.ActiveBinds {
|
||||
slog.Debug("Current bind: ", "id", bind.ID)
|
||||
b.updaters[bind.ID](&b.data.Values[bind.ID])
|
||||
}
|
||||
|
||||
// Set up virtual binds
|
||||
slog.Debug("Entering virtual binds loop")
|
||||
for _, vBind := range b.data.VirtualBinds {
|
||||
// NOTE: delete the logs here, they are really bad
|
||||
slog.Debug("Processing virtual binds")
|
||||
vBind.Process(b.data)
|
||||
}
|
||||
|
||||
b.data.PenultimateDataPoll = b.data.LastDataPoll
|
||||
b.data.LastDataPoll = time.Now()
|
||||
}
|
||||
|
||||
func (b *BeamNG) stream(ctx context.Context) <-chan telemetry.TelemetryData {
|
||||
b.data.InitialTime = time.Now()
|
||||
outCh := make(chan telemetry.TelemetryData)
|
||||
b.wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer b.wg.Done()
|
||||
defer close(outCh)
|
||||
|
||||
for {
|
||||
// Explicitly intercept cancellation
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-b.ticker.C:
|
||||
slog.Debug("READING DATA")
|
||||
b.readData()
|
||||
slog.Debug("READ DATA")
|
||||
|
||||
// Publish data
|
||||
select {
|
||||
case outCh <- *b.data:
|
||||
slog.Debug("PUBLISHED DATA")
|
||||
default:
|
||||
// skip this data, don't allow publishers to lag behind
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return outCh
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package beamng
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
conv "esdi/conversions"
|
||||
|
||||
"esdi/telemetry"
|
||||
)
|
||||
|
||||
const (
|
||||
LapTimeFormatStr = "04:05.000"
|
||||
)
|
||||
|
||||
func (b *BeamNG) unused(out *telemetry.TelemetryField) {
|
||||
out.Unused()
|
||||
}
|
||||
|
||||
func (b *BeamNG) updateSpeed(out *telemetry.TelemetryField) {
|
||||
out.Type = telemetry.DataTypeUINT16
|
||||
out.Raw = uint64(conv.MsToKph(b.og.Speed))
|
||||
}
|
||||
|
||||
func (b *BeamNG) updateGear(out *telemetry.TelemetryField) {
|
||||
out.Type = telemetry.DataTypeSTRING
|
||||
// NOTE: stupid idea but we can cache these values
|
||||
out.Str = strconv.Itoa(int(b.og.Gear))
|
||||
}
|
||||
|
||||
func (b *BeamNG) updateRPM(out *telemetry.TelemetryField) {
|
||||
out.Type = telemetry.DataTypeUINT16
|
||||
out.Raw = uint64(uint16(b.og.RPM))
|
||||
}
|
||||
|
||||
func (b *BeamNG) fuelLevel(out *telemetry.TelemetryField) {
|
||||
telemetry.FloatToStringTransform(b.og.Fuel, out)
|
||||
}
|
||||
|
||||
func (b *BeamNG) oilPressure(out *telemetry.TelemetryField) {
|
||||
telemetry.FloatToStringTransform(b.og.OilPressure, out)
|
||||
}
|
||||
|
||||
func (b *BeamNG) oilTemp(out *telemetry.TelemetryField) {
|
||||
telemetry.FloatToStringTransform(b.og.OilTemp, out)
|
||||
}
|
||||
|
||||
func (b *BeamNG) engTemp(out *telemetry.TelemetryField) {
|
||||
telemetry.FloatToStringTransform(b.og.EngTemp, out)
|
||||
}
|
||||
|
||||
// NOTE: find how to empty this
|
||||
func (b *BeamNG) pitSpeedLimiter(out *telemetry.TelemetryField) {
|
||||
}
|
||||
|
||||
func (b *BeamNG) leftIndicator(out *telemetry.TelemetryField) {
|
||||
chr := ' '
|
||||
if b.og.LeftIndicator() {
|
||||
chr = '<'
|
||||
}
|
||||
|
||||
out.Type = telemetry.DataTypeCHAR
|
||||
out.Raw = uint64(chr)
|
||||
}
|
||||
|
||||
func (b *BeamNG) rightIndicator(out *telemetry.TelemetryField) {
|
||||
chr := ' '
|
||||
if b.og.RightIndicator() {
|
||||
chr = '>'
|
||||
}
|
||||
|
||||
out.Type = telemetry.DataTypeCHAR
|
||||
out.Raw = uint64(chr)
|
||||
}
|
||||
|
||||
func (b *BeamNG) absLight(out *telemetry.TelemetryField) {
|
||||
chr := ' '
|
||||
if b.og.ABS() {
|
||||
chr = 'A'
|
||||
}
|
||||
|
||||
out.Type = telemetry.DataTypeCHAR
|
||||
out.Raw = uint64(chr)
|
||||
}
|
||||
|
||||
func (b *BeamNG) handbrakeLight(out *telemetry.TelemetryField) {
|
||||
chr := ' '
|
||||
if b.og.Handbrake() {
|
||||
chr = 'P'
|
||||
}
|
||||
|
||||
out.Type = telemetry.DataTypeCHAR
|
||||
out.Raw = uint64(chr)
|
||||
}
|
||||
|
||||
func (b *BeamNG) tcLight(out *telemetry.TelemetryField) {
|
||||
chr := ' '
|
||||
if b.og.TractionControl() {
|
||||
chr = 'T'
|
||||
}
|
||||
|
||||
out.Type = telemetry.DataTypeCHAR
|
||||
out.Raw = uint64(chr)
|
||||
}
|
||||
|
||||
func (b *BeamNG) batteryLight(out *telemetry.TelemetryField) {
|
||||
chr := ' '
|
||||
if b.og.BatteryLight() {
|
||||
chr = 'B'
|
||||
}
|
||||
|
||||
out.Type = telemetry.DataTypeCHAR
|
||||
out.Raw = uint64(chr)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package beamng
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
func IsRunning() bool {
|
||||
// TODO: The address should be loaded from some type of configuration
|
||||
addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:4444")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
conn, err := net.ListenUDP("udp", addr)
|
||||
defer conn.Close()
|
||||
if err != nil {
|
||||
slog.Debug("failed to listen to udp socket: " + err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
buf := make([]byte, 512)
|
||||
conn.SetReadDeadline(time.Now().Add(50 * time.Millisecond))
|
||||
|
||||
n, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Think of a better number or something
|
||||
return n >= 80
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package iracing
|
||||
|
||||
import (
|
||||
telem "esdi/telemetry"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
LapTimeFormatStr = "04:05.000"
|
||||
)
|
||||
|
||||
func LapTimeTransform(v any, out *telem.TelemetryField) {
|
||||
lapTimeInSeconds := v.(float32)
|
||||
|
||||
if lapTimeInSeconds < 0 {
|
||||
lapTimeInSeconds = 0
|
||||
}
|
||||
|
||||
wholeSeconds := int64(lapTimeInSeconds)
|
||||
lapTime := time.Unix(wholeSeconds, int64((lapTimeInSeconds-float32(wholeSeconds))*1e9))
|
||||
|
||||
out.Type = telem.DataTypeSTRING
|
||||
out.Str = lapTime.Format(LapTimeFormatStr)
|
||||
}
|
||||
|
||||
func EmptyTransform(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeCHAR
|
||||
out.Raw = uint64('-')
|
||||
}
|
||||
|
||||
func PitSpeedLimiterTransform(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeSTRING
|
||||
if v.(bool) {
|
||||
out.Str = "PIT"
|
||||
} else {
|
||||
out.Str = " "
|
||||
}
|
||||
}
|
||||
|
||||
func UInt8Transform(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeUINT8
|
||||
|
||||
if v == nil {
|
||||
out.Raw = 0
|
||||
return
|
||||
}
|
||||
|
||||
out.Raw = uint64(v.(int))
|
||||
}
|
||||
|
||||
func FloatToStringTransform(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeSTRING
|
||||
|
||||
if v == nil {
|
||||
out.Str = "inv"
|
||||
return
|
||||
}
|
||||
|
||||
out.Str = strconv.FormatFloat(float64(v.(float32)), 'f', 1, 32)
|
||||
}
|
||||
|
||||
func FloatToUInt8Transform(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeUINT8
|
||||
|
||||
if v == nil {
|
||||
out.Raw = uint64(0)
|
||||
return
|
||||
}
|
||||
|
||||
out.Raw = uint64(v.(float32))
|
||||
}
|
||||
@@ -2,44 +2,23 @@ package iracing
|
||||
|
||||
// This file maps the data from the desktop provider data structure to iRacing
|
||||
|
||||
import (
|
||||
"esdi/telemetry"
|
||||
)
|
||||
|
||||
var internalToSDKFieldNames = map[telemetry.FieldID]string{
|
||||
telemetry.Speed: "Speed",
|
||||
telemetry.Gear: "Gear",
|
||||
telemetry.RPM: "RPM",
|
||||
telemetry.FuelLevel: "FuelLevel",
|
||||
// Engine Data
|
||||
telemetry.OilPress: "OilPress",
|
||||
telemetry.OilTemp: "OilTemp",
|
||||
telemetry.WaterTemp: "WaterTemp",
|
||||
// Engine Warnings
|
||||
telemetry.PitSpeedLimiter: "irsdk_pitSpeedLimiter",
|
||||
// Ajudstements
|
||||
telemetry.BrakeBias: "dcBrakeBias",
|
||||
telemetry.ABSSetting: "dcABS",
|
||||
telemetry.TCSetting: "dcTractionControl",
|
||||
telemetry.ThrottleSetting: "dcThrottleShape",
|
||||
// Lap Data
|
||||
telemetry.LapLastLapTime: "LapLastLapTime",
|
||||
telemetry.LapNumber: "Lap",
|
||||
// Tire data
|
||||
telemetry.LFtempL: "LFtempCL",
|
||||
telemetry.LFtempM: "LFtempCM",
|
||||
telemetry.LFtempR: "LFtempCR",
|
||||
telemetry.RFtempL: "RFtempCL",
|
||||
telemetry.RFtempM: "RFtempCM",
|
||||
telemetry.RFtempR: "RFtempCR",
|
||||
telemetry.LRtempL: "LRtempCL",
|
||||
telemetry.LRtempM: "LRtempCM",
|
||||
telemetry.LRtempR: "LRtempCR",
|
||||
telemetry.RRtempL: "RRtempCL",
|
||||
telemetry.RRtempM: "RRtempCM",
|
||||
telemetry.RRtempR: "RRtempCR",
|
||||
// Session Data
|
||||
telemetry.SessionTime: "SessionTime",
|
||||
telemetry.ReplaySessionTime: "ReplaySessionTime",
|
||||
telemetry.Empty: "empty",
|
||||
}
|
||||
// TODO: pass these to the new Updaters system
|
||||
// var internalToSDKFieldNames = map[telemetry.FieldID]string{
|
||||
// // Tire data
|
||||
// telemetry.LFtempL: "LFtempCL",
|
||||
// telemetry.LFtempM: "LFtempCM",
|
||||
// telemetry.LFtempR: "LFtempCR",
|
||||
// telemetry.RFtempL: "RFtempCL",
|
||||
// telemetry.RFtempM: "RFtempCM",
|
||||
// telemetry.RFtempR: "RFtempCR",
|
||||
// telemetry.LRtempL: "LRtempCL",
|
||||
// telemetry.LRtempM: "LRtempCM",
|
||||
// telemetry.LRtempR: "LRtempCR",
|
||||
// telemetry.RRtempL: "RRtempCL",
|
||||
// telemetry.RRtempM: "RRtempCM",
|
||||
// telemetry.RRtempR: "RRtempCR",
|
||||
// // Session Data
|
||||
// telemetry.SessionTime: "SessionTime",
|
||||
// telemetry.ReplaySessionTime: "ReplaySessionTime",
|
||||
// telemetry.Empty: "empty",
|
||||
// }
|
||||
|
||||
+146
-155
@@ -7,109 +7,174 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
conv "esdi/conversions"
|
||||
telem "esdi/telemetry"
|
||||
"esdi/telemetry"
|
||||
|
||||
"github.com/ESilva15/goirsdk"
|
||||
)
|
||||
|
||||
const (
|
||||
NAME = "iRacing"
|
||||
)
|
||||
|
||||
// IRacing is our iRacing telemetry data provider - its a TelemetryProvider interface
|
||||
type IRacing struct {
|
||||
logger *slog.Logger
|
||||
SDK *goirsdk.IBT
|
||||
|
||||
// Data Handling
|
||||
mut sync.Mutex
|
||||
data *telem.TelemetryData
|
||||
mut sync.Mutex
|
||||
data *telemetry.TelemetryData
|
||||
updaters [telemetry.MaxFields]func(*telemetry.TelemetryField)
|
||||
|
||||
// Timing information
|
||||
ticker *time.Ticker // ticker will keep polling intervals constant
|
||||
|
||||
// Stream
|
||||
streamCh chan telem.TelemetryData
|
||||
wg sync.WaitGroup
|
||||
// streamCh chan telemetry.TelemetryData
|
||||
streamCancel context.CancelFunc
|
||||
}
|
||||
|
||||
func NewIRacingProvider(
|
||||
logger *slog.Logger,
|
||||
source string,
|
||||
telemOut string,
|
||||
yamlOut string,
|
||||
opts goirsdk.Options,
|
||||
) (*IRacing, error) {
|
||||
var err error
|
||||
|
||||
// Open the input file if provided - otherwise live telemetry was requested
|
||||
// Maybe this can be changed so we don't have to run it with these ifs but by configuring our
|
||||
// provider
|
||||
var file goirsdk.Reader = nil
|
||||
if source != "" {
|
||||
file, err = os.Open(source)
|
||||
if err != nil {
|
||||
return &IRacing{}, err
|
||||
// log.Fatalf("Failed to open IBT file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
sdk, err := goirsdk.Init(file, telemOut, yamlOut)
|
||||
sdk, err := goirsdk.Init(opts)
|
||||
if err != nil {
|
||||
logger.Error("failed to open the IRSDK instance")
|
||||
return &IRacing{}, err
|
||||
}
|
||||
|
||||
return &IRacing{
|
||||
logger: logger,
|
||||
SDK: sdk,
|
||||
data: telem.NewTelemetryData(),
|
||||
streamCh: make(chan telem.TelemetryData),
|
||||
provider := &IRacing{
|
||||
logger: logger,
|
||||
SDK: sdk,
|
||||
data: telemetry.NewTelemetryData(),
|
||||
// streamCh: make(chan telemetry.TelemetryData, 1),
|
||||
// NOTE: This is because I stupidly recorded a test IBT file in 240
|
||||
// TODO: make this configurable from the user side
|
||||
ticker: time.NewTicker(time.Second / 240),
|
||||
}, nil
|
||||
}
|
||||
|
||||
provider.updaters = [telemetry.MaxFields]func(*telemetry.TelemetryField){
|
||||
telemetry.Speed: provider.speed,
|
||||
telemetry.Gear: provider.gear,
|
||||
telemetry.RPM: provider.rpm,
|
||||
telemetry.FuelLevel: provider.fuelLevel,
|
||||
// Engine Data
|
||||
telemetry.OilPress: provider.oilPress,
|
||||
telemetry.OilTemp: provider.oilTemp,
|
||||
telemetry.WaterTemp: provider.waterTemp,
|
||||
// EngineWarnings
|
||||
telemetry.PitSpeedLimiter: provider.pitSpeedLimiter,
|
||||
// Adjustements
|
||||
telemetry.BrakeBias: provider.brakeBias,
|
||||
telemetry.ABSSetting: provider.absSetting,
|
||||
telemetry.TCSetting: provider.tcSetting,
|
||||
telemetry.ThrottleSetting: provider.throttleSetting,
|
||||
// Lap Data
|
||||
telemetry.LapLastLapTime: provider.lapTime,
|
||||
telemetry.LapNumber: provider.lapNumber,
|
||||
// case telemetry.LFtempM:
|
||||
// binding.Transform = func(v any, out *telemetry.TelemetryField) {
|
||||
// out.Type = telemetry.DataTypeSTRING
|
||||
// out.Str = strconv.FormatFloat(float64(v.(float32)), 'f', 1, 32)
|
||||
// }
|
||||
// case telemetry.SessionTime:
|
||||
// binding.Transform = func(v any, out *telemetry.TelemetryField) {
|
||||
// out.Type = telemetry.DataTypeSTRING
|
||||
// out.Str = strconv.FormatFloat(v.(float64), 'f', 1, 32)
|
||||
// }
|
||||
// case telemetry.ReplaySessionTime:
|
||||
// binding.Transform = func(v any, out *telemetry.TelemetryField) {
|
||||
// out.Type = telemetry.DataTypeSTRING
|
||||
// out.Str = strconv.FormatFloat(v.(float64), 'f', 1, 32)
|
||||
// }
|
||||
// case telemetry.Empty:
|
||||
// binding.Transform = telemetry.EmptyTransform
|
||||
// }
|
||||
}
|
||||
|
||||
// Set the unset telemetry fields on the updaters as unused fields
|
||||
for k := range int(telemetry.MaxFields) {
|
||||
if provider.updaters[k] == nil {
|
||||
provider.updaters[k] = provider.unused
|
||||
}
|
||||
}
|
||||
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (i *IRacing) Close() {
|
||||
// Need to find a way of gracefully closing the channel
|
||||
// close(i.streamCh)
|
||||
i.SDK.Close()
|
||||
i.ticker.Stop()
|
||||
}
|
||||
|
||||
func (i *IRacing) isDataAvailable() bool {
|
||||
// Its offline telemetry, data must be available
|
||||
if i.SDK.File != nil {
|
||||
return true
|
||||
if i.SDK.File == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if live telemetry is on
|
||||
if i.SDK.IsConnected() {
|
||||
return true
|
||||
if !i.SDK.IsConnected() {
|
||||
return false
|
||||
}
|
||||
|
||||
return false
|
||||
return true
|
||||
}
|
||||
|
||||
func (i *IRacing) stream(ctx context.Context) {
|
||||
func (i *IRacing) stream(ctx context.Context) <-chan telemetry.TelemetryData {
|
||||
i.data.InitialTime = time.Now()
|
||||
outCh := make(chan telemetry.TelemetryData)
|
||||
i.wg.Add(1)
|
||||
|
||||
go func() {
|
||||
for {
|
||||
// We start by checking if we do or do not have data available
|
||||
if !i.isDataAvailable() {
|
||||
continue
|
||||
}
|
||||
defer i.wg.Done()
|
||||
defer close(outCh)
|
||||
|
||||
// Put this into the configuration file
|
||||
consecutiveTimeouts := 0
|
||||
maxTimeouts := 30
|
||||
dataEvTimeout := 100
|
||||
for {
|
||||
// Explicitly intercept cancellation
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-i.ticker.C:
|
||||
default:
|
||||
}
|
||||
|
||||
if i.SDK.CheckForDataEvent(time.Duration(dataEvTimeout) * time.Millisecond) {
|
||||
consecutiveTimeouts = 0
|
||||
i.readData()
|
||||
|
||||
// Publish data
|
||||
select {
|
||||
case i.streamCh <- *i.data:
|
||||
case outCh <- *i.data:
|
||||
default:
|
||||
// skip this data, don't allow publishers to lag behind
|
||||
}
|
||||
} else {
|
||||
consecutiveTimeouts++
|
||||
if consecutiveTimeouts >= maxTimeouts {
|
||||
i.logger.Info("Telemetry stream stalled")
|
||||
if i.streamCancel != nil {
|
||||
i.streamCancel()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return outCh
|
||||
}
|
||||
|
||||
func (i *IRacing) readData() {
|
||||
@@ -123,18 +188,13 @@ func (i *IRacing) readData() {
|
||||
return
|
||||
}
|
||||
|
||||
// Read 1 to 1 data
|
||||
for _, b := range i.data.ActiveBinds {
|
||||
v := i.SDK.Vars.Vars[b.Key].Value
|
||||
|
||||
b.Transform(v, &i.data.Values[b.ID])
|
||||
// Read 1 to 1 data using our updaters
|
||||
for _, bind := range i.data.ActiveBinds {
|
||||
i.updaters[bind.ID](&i.data.Values[bind.ID])
|
||||
}
|
||||
|
||||
// Set up virtual binds
|
||||
i.logger.Debug("Entering virtual binds loop")
|
||||
for _, vBind := range i.data.VirtualBinds {
|
||||
// NOTE: delete the logs here, they are really bad
|
||||
i.logger.Debug("Processing virtual binds")
|
||||
vBind.Process(i.data)
|
||||
}
|
||||
|
||||
@@ -146,41 +206,49 @@ func (i *IRacing) readData() {
|
||||
|
||||
// Stream returns a channel that we will use to funnel the telemetry data back to the
|
||||
// UI, which then should broadcast it to the devices
|
||||
func (i *IRacing) Stream() (<-chan telem.TelemetryData, error) {
|
||||
func (i *IRacing) Stream() (<-chan telemetry.TelemetryData, error) {
|
||||
var ctx context.Context
|
||||
ctx, i.streamCancel = context.WithCancel(context.Background())
|
||||
|
||||
// Start the stream
|
||||
i.stream(ctx)
|
||||
ch := i.stream(ctx)
|
||||
|
||||
return i.streamCh, nil
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (i *IRacing) Subscribe(requestFields map[int16]telem.FieldID) {
|
||||
func (i *IRacing) StopStream() {
|
||||
if i.streamCancel == nil {
|
||||
return
|
||||
}
|
||||
|
||||
i.streamCancel()
|
||||
i.wg.Wait()
|
||||
i.streamCancel = nil
|
||||
}
|
||||
|
||||
func (i *IRacing) Subscribe(requestFields []telemetry.FieldID) {
|
||||
i.logger.Debug(fmt.Sprintf("Len Req: %d\n", len(requestFields)))
|
||||
|
||||
i.data.ActiveBinds = make([]telem.BoundField, 0, len(requestFields))
|
||||
i.data.ActiveBinds = make([]telemetry.BoundField, 0, len(requestFields))
|
||||
|
||||
// First we must add the virtual fields
|
||||
// we will add their dependencies and the primitives to a slice
|
||||
pendingBinds := make([]telem.FieldID, telem.MaxFields)
|
||||
|
||||
for winID, id := range requestFields {
|
||||
i.data.Values[id].IDs = append(i.data.Values[id].IDs, winID)
|
||||
pendingBinds := make([]telemetry.FieldID, 0, telemetry.MaxFields)
|
||||
|
||||
for _, id := range requestFields {
|
||||
switch id {
|
||||
case telem.RPMStateColour:
|
||||
i.data.VirtualBinds = append(i.data.VirtualBinds, telem.NewRPMLights())
|
||||
case telem.FCCurrentLap:
|
||||
case telemetry.RPMStateColour:
|
||||
i.data.VirtualBinds = append(i.data.VirtualBinds, telemetry.NewRPMLights())
|
||||
case telemetry.FCCurrentLap:
|
||||
i.data.VirtualBinds = append(i.data.VirtualBinds,
|
||||
telem.NewFuelCalculator(i.logger.WithGroup("FUEL CALC")))
|
||||
telemetry.NewFuelCalculator(i.logger.WithGroup("FUEL CALC")))
|
||||
default:
|
||||
// primitive telemetry field
|
||||
pendingBinds = append(pendingBinds, id)
|
||||
}
|
||||
}
|
||||
|
||||
boundCheck := make(map[telem.FieldID]bool)
|
||||
boundCheck := make(map[telemetry.FieldID]bool)
|
||||
|
||||
// Now that we know all the fields we need to bind we follow the binding procedure
|
||||
for _, id := range pendingBinds {
|
||||
@@ -189,97 +257,8 @@ func (i *IRacing) Subscribe(requestFields map[int16]telem.FieldID) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Translate the UI FieldIDs to this provider's field names
|
||||
sdkKey, ok := internalToSDKFieldNames[id]
|
||||
if !ok {
|
||||
i.logger.Debug("failed to get internal id")
|
||||
// Need to find a way to pass a message saying something wasn't right
|
||||
continue
|
||||
}
|
||||
|
||||
binding := telem.BoundField{
|
||||
Key: sdkKey,
|
||||
ID: id,
|
||||
}
|
||||
|
||||
switch id {
|
||||
case telem.Speed:
|
||||
binding.Transform = func(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeUINT16
|
||||
out.Raw = uint64(conv.MsToKph(v.(float32)))
|
||||
}
|
||||
case telem.Gear:
|
||||
binding.Transform = func(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeCHAR
|
||||
// out.Raw = uint64(v.(int))
|
||||
|
||||
gear := 0
|
||||
if val, ok := v.(int32); ok {
|
||||
gear = int(val)
|
||||
} else if val, ok := v.(int); ok {
|
||||
gear = val
|
||||
}
|
||||
|
||||
switch {
|
||||
case gear == 0:
|
||||
out.Raw = uint64('N') // ASCII 78
|
||||
case gear < 0:
|
||||
out.Raw = uint64('R') // ASCII 82
|
||||
case gear > 0 && gear < 10:
|
||||
// Quickest way to turn 1 into '1', 2 into '2', etc.
|
||||
// ASCII '0' is 48, so 48 + 1 = 49 ('1')
|
||||
out.Raw = uint64('0' + gear)
|
||||
default:
|
||||
out.Raw = uint64('?') // Fallback
|
||||
}
|
||||
}
|
||||
case telem.RPM:
|
||||
binding.Transform = func(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeUINT16
|
||||
out.Raw = uint64(uint16(v.(float32)))
|
||||
}
|
||||
case telem.FuelLevel:
|
||||
binding.Transform = FloatToStringTransform
|
||||
// Engine Data
|
||||
case telem.OilPress:
|
||||
binding.Transform = FloatToStringTransform
|
||||
case telem.OilTemp:
|
||||
binding.Transform = FloatToStringTransform
|
||||
case telem.WaterTemp:
|
||||
binding.Transform = FloatToStringTransform
|
||||
// Something else
|
||||
case telem.PitSpeedLimiter:
|
||||
binding.Transform = PitSpeedLimiterTransform
|
||||
// Adjustements
|
||||
case telem.BrakeBias:
|
||||
binding.Transform = FloatToStringTransform
|
||||
case telem.ABSSetting:
|
||||
binding.Transform = FloatToUInt8Transform
|
||||
case telem.TCSetting:
|
||||
binding.Transform = FloatToUInt8Transform
|
||||
case telem.ThrottleSetting:
|
||||
binding.Transform = FloatToUInt8Transform
|
||||
case telem.LFtempM:
|
||||
binding.Transform = func(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeSTRING
|
||||
out.Str = strconv.FormatFloat(float64(v.(float32)), 'f', 1, 32)
|
||||
}
|
||||
case telem.SessionTime:
|
||||
binding.Transform = func(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeSTRING
|
||||
out.Str = strconv.FormatFloat(v.(float64), 'f', 1, 32)
|
||||
}
|
||||
case telem.ReplaySessionTime:
|
||||
binding.Transform = func(v any, out *telem.TelemetryField) {
|
||||
out.Type = telem.DataTypeSTRING
|
||||
out.Str = strconv.FormatFloat(v.(float64), 'f', 1, 32)
|
||||
}
|
||||
case telem.Empty:
|
||||
binding.Transform = EmptyTransform
|
||||
case telem.LapLastLapTime:
|
||||
binding.Transform = LapTimeTransform
|
||||
case telem.LapNumber:
|
||||
binding.Transform = UInt8Transform
|
||||
binding := telemetry.BoundField{
|
||||
ID: id,
|
||||
}
|
||||
|
||||
i.data.ActiveBinds = append(i.data.ActiveBinds, binding)
|
||||
@@ -288,3 +267,15 @@ func (i *IRacing) Subscribe(requestFields map[int16]telem.FieldID) {
|
||||
|
||||
i.logger.Debug(fmt.Sprintf("Subscribed: %+v\n", i.data.ActiveBinds))
|
||||
}
|
||||
|
||||
func (i *IRacing) Name() string {
|
||||
return NAME
|
||||
}
|
||||
|
||||
func (i *IRacing) IsAlive(timeout time.Duration) bool {
|
||||
if !i.SDK.CheckForDataEvent(timeout) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package iracing
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
conv "esdi/conversions"
|
||||
"esdi/telemetry"
|
||||
|
||||
"github.com/ESilva15/goirsdk"
|
||||
)
|
||||
|
||||
const (
|
||||
LapTimeFormatStr = "04:05.000"
|
||||
)
|
||||
|
||||
func getVar[T any](
|
||||
vars map[string]goirsdk.Var,
|
||||
key string,
|
||||
fallback T,
|
||||
logger *slog.Logger,
|
||||
) T {
|
||||
raw, ok := vars[key]
|
||||
if !ok {
|
||||
logger.Error("key not present in map", "key", key)
|
||||
return fallback
|
||||
}
|
||||
|
||||
val, ok := raw.Value.(T)
|
||||
if !ok {
|
||||
logger.Error("could not cast value", "key", key, "val", raw)
|
||||
return fallback
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
|
||||
func (i *IRacing) unused(out *telemetry.TelemetryField) {
|
||||
out.Unused()
|
||||
}
|
||||
|
||||
func (i *IRacing) speed(out *telemetry.TelemetryField) {
|
||||
speed := getVar(i.SDK.Vars.Vars, "Speed", float32(0), i.logger)
|
||||
|
||||
out.Type = telemetry.DataTypeUINT16
|
||||
out.Raw = uint64(conv.MsToKph(speed))
|
||||
}
|
||||
|
||||
func (i *IRacing) gear(out *telemetry.TelemetryField) {
|
||||
gear := getVar(i.SDK.Vars.Vars, "Gear", int(0), i.logger)
|
||||
|
||||
out.Type = telemetry.DataTypeCHAR
|
||||
|
||||
switch {
|
||||
case gear == 0:
|
||||
out.Raw = uint64('N')
|
||||
case gear == -1:
|
||||
out.Raw = uint64('R')
|
||||
case gear > 0:
|
||||
out.Raw = uint64('0' + gear)
|
||||
default:
|
||||
out.Raw = uint64('?') // Fallback
|
||||
}
|
||||
}
|
||||
|
||||
func (i *IRacing) rpm(out *telemetry.TelemetryField) {
|
||||
rpm := getVar(i.SDK.Vars.Vars, "RPM", float32(0), i.logger)
|
||||
|
||||
out.Type = telemetry.DataTypeUINT16
|
||||
out.Raw = uint64(uint16(rpm))
|
||||
}
|
||||
|
||||
func (i *IRacing) fuelLevel(out *telemetry.TelemetryField) {
|
||||
fuelLevel := getVar(i.SDK.Vars.Vars, "FuelLevel", float32(-1.0), i.logger)
|
||||
telemetry.FloatToStringTransform(fuelLevel, out)
|
||||
}
|
||||
|
||||
// EngineWarnings
|
||||
func (i *IRacing) pitSpeedLimiter(out *telemetry.TelemetryField) {
|
||||
out.Type = telemetry.DataTypeSTRING
|
||||
out.Str = " "
|
||||
|
||||
if i.SDK.PitSpeedLimiter() {
|
||||
out.Str = "PIT"
|
||||
}
|
||||
}
|
||||
|
||||
// EngineData ↓
|
||||
func (i *IRacing) oilPress(out *telemetry.TelemetryField) {
|
||||
oilPress := getVar(i.SDK.Vars.Vars, "OilPress", float32(-1.0), i.logger)
|
||||
telemetry.FloatToStringTransform(oilPress, out)
|
||||
}
|
||||
|
||||
func (i *IRacing) oilTemp(out *telemetry.TelemetryField) {
|
||||
oilTemp := getVar(i.SDK.Vars.Vars, "OilTemp", float32(-1.0), i.logger)
|
||||
telemetry.FloatToStringTransform(oilTemp, out)
|
||||
}
|
||||
|
||||
func (i *IRacing) waterTemp(out *telemetry.TelemetryField) {
|
||||
waterTemp := getVar(i.SDK.Vars.Vars, "WaterTemp", float32(-1.0), i.logger)
|
||||
telemetry.FloatToStringTransform(waterTemp, out)
|
||||
}
|
||||
|
||||
// EngineData ↑
|
||||
|
||||
// Adjustments ↓
|
||||
func (i *IRacing) brakeBias(out *telemetry.TelemetryField) {
|
||||
bb := getVar(i.SDK.Vars.Vars, "dcBrakeBias", float32(-1.0), i.logger)
|
||||
telemetry.FloatToStringTransform(bb, out)
|
||||
}
|
||||
|
||||
func (i *IRacing) absSetting(out *telemetry.TelemetryField) {
|
||||
abs := getVar(i.SDK.Vars.Vars, "dcABS", float32(-1.0), i.logger)
|
||||
telemetry.FloatToUInt8Transform(abs, out)
|
||||
}
|
||||
|
||||
func (i *IRacing) tcSetting(out *telemetry.TelemetryField) {
|
||||
tc := getVar(i.SDK.Vars.Vars, "dcTractionControl", float32(-1.0), i.logger)
|
||||
telemetry.FloatToUInt8Transform(tc, out)
|
||||
}
|
||||
|
||||
func (i *IRacing) throttleSetting(out *telemetry.TelemetryField) {
|
||||
throttle := getVar(i.SDK.Vars.Vars, "dcThrottleShape", float32(-1.0), i.logger)
|
||||
telemetry.FloatToUInt8Transform(throttle, out)
|
||||
}
|
||||
|
||||
// Adjustments ↑
|
||||
|
||||
// Laps ↓
|
||||
func (i *IRacing) lapTime(out *telemetry.TelemetryField) {
|
||||
lapTimeInSeconds := getVar(i.SDK.Vars.Vars, "LapLastLapTime", float32(0), i.logger)
|
||||
|
||||
if lapTimeInSeconds < 0 {
|
||||
lapTimeInSeconds = 0
|
||||
}
|
||||
|
||||
wholeSeconds := int64(lapTimeInSeconds)
|
||||
lapTime := time.Unix(wholeSeconds, int64((lapTimeInSeconds-float32(wholeSeconds))*1e9))
|
||||
|
||||
out.Type = telemetry.DataTypeSTRING
|
||||
out.Str = lapTime.Format(LapTimeFormatStr)
|
||||
}
|
||||
|
||||
func (i *IRacing) lapNumber(out *telemetry.TelemetryField) {
|
||||
lapNumber := getVar(i.SDK.Vars.Vars, "Lap", int(0), i.logger)
|
||||
telemetry.UInt8Transform(lapNumber, out)
|
||||
}
|
||||
|
||||
// Laps ↑
|
||||
@@ -0,0 +1,32 @@
|
||||
package iracing
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/ESilva15/goirsdk"
|
||||
eventutils "github.com/ESilva15/goirsdk/eventutils"
|
||||
)
|
||||
|
||||
func IsRunning() bool {
|
||||
irUtils, err := eventutils.Init()
|
||||
if err != nil {
|
||||
// we need error validation or something here
|
||||
return false
|
||||
}
|
||||
defer irUtils.Close()
|
||||
|
||||
if err := irUtils.OpenEvent(goirsdk.IRSDK_DATAVALIDEVENTNAME); err != nil {
|
||||
// we need error validation or something here
|
||||
return false
|
||||
}
|
||||
|
||||
// We now check for some consecutive data events
|
||||
for range 3 {
|
||||
if !irUtils.CheckValidDataEvent(1 * time.Second) {
|
||||
// slog.Debug("Timed out waiting for DataValidEvent")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Package providers
|
||||
package providers
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
|
||||
"esdi/providers/beamng"
|
||||
"esdi/providers/iracing"
|
||||
"esdi/telemetry"
|
||||
|
||||
bngsdk "github.com/ESilva15/gobngsdk"
|
||||
"github.com/ESilva15/goirsdk"
|
||||
)
|
||||
|
||||
// Make this be some kind of struct where we can access a function that returns
|
||||
// the selected provider by its name
|
||||
type Provider struct {
|
||||
Name string
|
||||
NewProvider func(*slog.Logger) (telemetry.TelemetryProvider, error)
|
||||
IsRunning func() bool // To check if this provider is up and running
|
||||
}
|
||||
|
||||
var Providers = map[string]Provider{
|
||||
beamng.NAME: {
|
||||
Name: beamng.NAME,
|
||||
NewProvider: NewBeamNGProvider,
|
||||
IsRunning: beamng.IsRunning,
|
||||
},
|
||||
iracing.NAME: {
|
||||
Name: iracing.NAME,
|
||||
NewProvider: NewLiveIRacingProvider,
|
||||
IsRunning: iracing.IsRunning,
|
||||
},
|
||||
}
|
||||
|
||||
func NewLiveIRacingProvider(logger *slog.Logger) (telemetry.TelemetryProvider, error) {
|
||||
provider, err := iracing.NewIRacingProvider(logger, goirsdk.Options{
|
||||
Logger: logger,
|
||||
SourceType: goirsdk.SharedMemoryFile,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("failed to create iRacing provider", "err", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func NewBeamNGProvider(logger *slog.Logger) (telemetry.TelemetryProvider, error) {
|
||||
// TODO: these should come from some kind of config
|
||||
provider, err := beamng.NewBeamNGProvider(logger, &bngsdk.Options{
|
||||
Logger: logger.With("TelemetryProvider", beamng.NAME),
|
||||
SourceType: bngsdk.UDPData,
|
||||
ImportUDPAddress: "127.0.0.1",
|
||||
ImportUDPPort: 4444,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("failed to create BeamNG provider", "err", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return provider, nil
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"esdi/devices"
|
||||
"esdi/peripheral"
|
||||
"esdi/telemetry"
|
||||
)
|
||||
|
||||
var ErrPeripheralAlreadyRegistered = errors.New("peripheral is already registered")
|
||||
|
||||
// DeviceService will handle sending the data from the telemetry service to the
|
||||
// actual devices
|
||||
// NOTE: create a virtual device and make it be the output window or something so
|
||||
// we can just add it as a device or whatever instead of being a custom made thing
|
||||
// that would be pretty cool I think
|
||||
type DeviceService struct {
|
||||
Logger *slog.Logger
|
||||
// Device discovery
|
||||
mu sync.RWMutex
|
||||
ctxDiscovery context.Context
|
||||
ctxDiscoveryCancel context.CancelFunc
|
||||
Devices map[string]peripheral.Peripheral
|
||||
// Strem handling
|
||||
streamCancel context.CancelFunc
|
||||
TelemCh <-chan telemetry.TelemetryData
|
||||
// Output
|
||||
Messages chan string
|
||||
}
|
||||
|
||||
func NewDeviceService(logger *slog.Logger) *DeviceService {
|
||||
sharedChannel := make(chan string, 10)
|
||||
|
||||
dev := &DeviceService{
|
||||
Devices: make(map[string]peripheral.Peripheral),
|
||||
Logger: logger,
|
||||
Messages: sharedChannel,
|
||||
}
|
||||
|
||||
// Start the routine that looks for devices - should always be running in the background
|
||||
// Create a routine to poll this provider while we wait to start the stream or pause it
|
||||
dev.ctxDiscovery, dev.ctxDiscoveryCancel = context.WithCancel(context.Background())
|
||||
go dev.FindDevices()
|
||||
|
||||
return dev
|
||||
}
|
||||
|
||||
func (ds *DeviceService) FindDevices() {
|
||||
// Need to define a list of devices to search for
|
||||
// For now lets just try to find our cdashdisplay - will think about the rest later
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ds.ctxDiscovery.Done():
|
||||
// If requested to cancel we cancel background discovery
|
||||
return
|
||||
case <-ticker.C:
|
||||
for pName, peripheral := range devices.List {
|
||||
if ds.DeviceExists(pName) {
|
||||
// We already discovered this device
|
||||
continue
|
||||
}
|
||||
|
||||
ds.Logger.Debug("looking for device", "name", pName)
|
||||
dev, err := peripheral.Discover()
|
||||
if err != nil {
|
||||
ds.Logger.Debug("didn't find device", "name", pName)
|
||||
continue
|
||||
}
|
||||
|
||||
// Register the device we just found
|
||||
ds.RegisterDevice(dev)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ds *DeviceService) RegisterDevice(dev peripheral.Peripheral) error {
|
||||
ds.mu.Lock()
|
||||
defer ds.mu.Unlock()
|
||||
|
||||
if ds.DeviceExists(dev.Name()) {
|
||||
return ErrPeripheralAlreadyRegistered
|
||||
}
|
||||
|
||||
ds.Devices[dev.Name()] = dev
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ds *DeviceService) GetDevice(name string) (peripheral.Peripheral, error) {
|
||||
val, ok := ds.Devices[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("device `%s` couldn't be found", name)
|
||||
}
|
||||
|
||||
return val, nil
|
||||
}
|
||||
|
||||
func (ds *DeviceService) DeviceExists(name string) bool {
|
||||
if _, ok := ds.Devices[name]; !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (ds *DeviceService) StartStream() {
|
||||
// NOTE: i'm using this pattern a whole lot. Maybe I can create a struct to handle this
|
||||
var ctx context.Context
|
||||
ctx, ds.streamCancel = context.WithCancel(context.Background())
|
||||
|
||||
go ds.transmit(ctx)
|
||||
}
|
||||
|
||||
func (ds *DeviceService) StopStream() {
|
||||
if ds.streamCancel == nil {
|
||||
return
|
||||
}
|
||||
|
||||
ds.streamCancel()
|
||||
ds.streamCancel = nil
|
||||
}
|
||||
|
||||
// SetTelemetryChannel sets the TelemCh to the passed channel
|
||||
func (ds *DeviceService) SetTelemetryChannel(ch <-chan telemetry.TelemetryData) {
|
||||
ds.TelemCh = ch
|
||||
}
|
||||
|
||||
// transmit will send the data to the devices themselves
|
||||
func (ds *DeviceService) transmit(ctx context.Context) {
|
||||
var isSending atomic.Bool
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case data, ok := <-ds.TelemCh:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if isSending.Load() {
|
||||
continue
|
||||
}
|
||||
|
||||
isSending.Store(true)
|
||||
|
||||
// TODO: make a copy of the data and send that copy instead of keeping
|
||||
// the data locked
|
||||
ds.mu.RLock()
|
||||
for _, dev := range ds.Devices {
|
||||
err := dev.SendData(&data)
|
||||
if err == peripheral.ErrDeviceTimedOut {
|
||||
// What do we do here?
|
||||
// TODO: somehow we need to handle reconnection
|
||||
}
|
||||
}
|
||||
ds.mu.RUnlock()
|
||||
|
||||
isSending.Store(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"esdi/providers"
|
||||
"esdi/telemetry"
|
||||
telem "esdi/telemetry"
|
||||
)
|
||||
|
||||
// TelemetryService will be our base struct to handle telemetry data
|
||||
// It should hook to a data sink and handle it like iRacing, BeamNG, AC and so on
|
||||
type TelemetryService struct {
|
||||
logger *slog.Logger
|
||||
devService *DeviceService
|
||||
// Streaming
|
||||
isStreaming bool
|
||||
// Concurrency protection
|
||||
mut sync.RWMutex
|
||||
activeProvider telem.TelemetryProvider
|
||||
isConnected bool
|
||||
// Channel for the UI
|
||||
listeners map[string]chan telem.TelemetryData
|
||||
cancelForward context.CancelFunc
|
||||
// Output window
|
||||
Messages chan string
|
||||
// Cancel looking for providers
|
||||
CtxMonitor context.Context
|
||||
cancelMonitor context.CancelFunc
|
||||
CtxHealthcheck context.Context
|
||||
healthCheckCancel context.CancelFunc
|
||||
}
|
||||
|
||||
func NewTelemetryService(logger *slog.Logger, devServo *DeviceService) *TelemetryService {
|
||||
sharedChannel := make(chan string, 10)
|
||||
newService := &TelemetryService{
|
||||
logger: logger,
|
||||
isConnected: false,
|
||||
devService: devServo,
|
||||
listeners: make(map[string]chan telem.TelemetryData),
|
||||
Messages: sharedChannel,
|
||||
}
|
||||
newService.CtxMonitor, newService.cancelMonitor = context.WithCancel(context.Background())
|
||||
|
||||
return newService
|
||||
}
|
||||
|
||||
func (t *TelemetryService) ProviderMonitor(ctx context.Context) {
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
slog.Info("checking if provider is still running")
|
||||
if !t.activeProvider.IsAlive(500 * time.Millisecond) {
|
||||
slog.Warn("provider healthcheck failed")
|
||||
t.dropActiveProvider()
|
||||
t.onProviderHealthCheckFailed()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Listener Control [START] ----------------------------------------------------
|
||||
|
||||
func (t *TelemetryService) SubscribeListener(id string, bufferSize int) <-chan telem.TelemetryData {
|
||||
t.mut.Lock()
|
||||
defer t.mut.Unlock()
|
||||
|
||||
// NOTE: is this truly necessary?
|
||||
// return the channel if it already exists
|
||||
if ch, exists := t.listeners[id]; exists {
|
||||
return ch
|
||||
}
|
||||
|
||||
ch := make(chan telem.TelemetryData, bufferSize)
|
||||
t.listeners[id] = ch
|
||||
|
||||
t.logger.Info("New stream subscriber registered", "id", id)
|
||||
return ch
|
||||
}
|
||||
|
||||
func (t *TelemetryService) UnsubscribeListener(id string) {
|
||||
t.mut.Lock()
|
||||
defer t.mut.Unlock()
|
||||
|
||||
if ch, exists := t.listeners[id]; exists {
|
||||
close(ch)
|
||||
delete(t.listeners, id)
|
||||
t.logger.Info("Stream subscriber removed", "id", id)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TelemetryService) SubscribeToFields() []telem.FieldID {
|
||||
seen := make(map[telemetry.FieldID]struct{})
|
||||
var allFields []telemetry.FieldID
|
||||
|
||||
for _, dev := range t.devService.Devices {
|
||||
for _, field := range dev.RequiredFields() {
|
||||
if _, exists := seen[field]; !exists {
|
||||
seen[field] = struct{}{}
|
||||
allFields = append(allFields, field)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.logger.Debug("requested fields", "fields", allFields)
|
||||
t.activeProvider.Subscribe(allFields)
|
||||
|
||||
return allFields
|
||||
}
|
||||
|
||||
// Listener Control [END] ------------------------------------------------------
|
||||
|
||||
// Provider Control [START] ----------------------------------------------------
|
||||
|
||||
func (t *TelemetryService) HasActiveProvider() bool {
|
||||
if t.activeProvider == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (t *TelemetryService) dropActiveProvider() {
|
||||
if t.cancelForward != nil {
|
||||
t.cancelForward()
|
||||
}
|
||||
|
||||
t.activeProvider.StopStream()
|
||||
t.activeProvider.Close()
|
||||
t.activeProvider = nil
|
||||
}
|
||||
|
||||
func (t *TelemetryService) SwitchProvider(newProvider telem.TelemetryProvider) error {
|
||||
t.mut.Lock()
|
||||
defer t.mut.Unlock()
|
||||
|
||||
// Clean up the current to be old provider
|
||||
if t.activeProvider != nil {
|
||||
t.dropActiveProvider()
|
||||
}
|
||||
|
||||
// Assign the new provider
|
||||
t.activeProvider = newProvider
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *TelemetryService) onProviderHealthCheckFailed() {
|
||||
// Just restart the whole lookup process
|
||||
go t.FindProvider(t.CtxMonitor)
|
||||
}
|
||||
|
||||
func (t *TelemetryService) onFindProvider(prov telem.TelemetryProvider) {
|
||||
// Attach to the provider
|
||||
t.logger.Info("found provider for " + prov.Name())
|
||||
err := t.SwitchProvider(prov)
|
||||
if err != nil {
|
||||
t.logger.Error("failed to switch to provider onFindProvider", "err", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Create a routine to poll this provider while we wait to start the stream or pause it
|
||||
t.CtxHealthcheck, t.healthCheckCancel = context.WithCancel(context.Background())
|
||||
go t.ProviderMonitor(t.CtxHealthcheck)
|
||||
}
|
||||
|
||||
func (t *TelemetryService) onProviderStopsMidStream() {
|
||||
// clear the current provider
|
||||
// TODO: now we need to also clear the devices to restart everything,
|
||||
// if the stream stopped we have to restart the devices and everything
|
||||
t.logger.Info("cleaning dropped provider and restarting lookup service")
|
||||
t.dropActiveProvider()
|
||||
go t.FindProvider(t.CtxMonitor)
|
||||
}
|
||||
|
||||
// TODO: add some way of retriggering this. Currently it should:
|
||||
// start monitoring on startup -> find provider -> stop monitoring (when game closes for example)
|
||||
func (t *TelemetryService) FindProvider(ctx context.Context) {
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
t.logger.Debug("monitoring for providers")
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
for _, prov := range providers.Providers {
|
||||
// t.logger.Debug("checking provider: " + prov.Name)
|
||||
provider, err := prov.NewProvider(t.logger)
|
||||
if err != nil {
|
||||
// Its not running
|
||||
continue
|
||||
}
|
||||
|
||||
if provider.IsAlive(500 * time.Millisecond) {
|
||||
t.onFindProvider(provider)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Provider Control [END] ------------------------------------------------------
|
||||
|
||||
// Streaming Control [START] ---------------------------------------------------
|
||||
|
||||
func (t *TelemetryService) StopStream() {
|
||||
t.mut.Lock()
|
||||
defer t.mut.Unlock()
|
||||
|
||||
if t.cancelForward != nil {
|
||||
t.cancelForward()
|
||||
t.cancelForward = nil
|
||||
}
|
||||
|
||||
t.activeProvider.StopStream()
|
||||
t.isStreaming = false
|
||||
}
|
||||
|
||||
func (t *TelemetryService) StartStream() {
|
||||
slog.Debug("Stream started")
|
||||
|
||||
// Start the new stream
|
||||
if t.activeProvider == nil {
|
||||
slog.Debug("there's no active provider. not starting the stream")
|
||||
return
|
||||
}
|
||||
|
||||
// Stop the provider healthcheck
|
||||
t.healthCheckCancel()
|
||||
|
||||
simInCh, _ := t.activeProvider.Stream()
|
||||
// TODO: the provider needs to be able to tell the data has stopped
|
||||
// so we can restart the provider lookup routine
|
||||
|
||||
// Create the context so we can control the lifecycle
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.cancelForward = cancel
|
||||
|
||||
// Multiplex this data
|
||||
go t.multiplexData(ctx, simInCh)
|
||||
t.isStreaming = true
|
||||
}
|
||||
|
||||
func (t *TelemetryService) multiplexData(ctx context.Context, dataCh <-chan telem.TelemetryData) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case data, ok := <-dataCh:
|
||||
if !ok {
|
||||
t.logger.Debug("something happened on the provider - stream closed")
|
||||
t.onProviderStopsMidStream()
|
||||
return
|
||||
}
|
||||
|
||||
t.mut.RLock()
|
||||
for _, ch := range t.listeners {
|
||||
// t.logger.Debug("sending data to listener", "listener", key, "data", data)
|
||||
select {
|
||||
case ch <- data:
|
||||
// Sends data to the subscriber
|
||||
default:
|
||||
// Subscriber is full, we just skip ahead. Maybe find a how to add metrics here
|
||||
}
|
||||
}
|
||||
t.mut.RUnlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TelemetryService) IsStreaming() bool {
|
||||
return t.isStreaming
|
||||
}
|
||||
|
||||
// Streaming Control [END] -----------------------------------------------------
|
||||
@@ -0,0 +1,41 @@
|
||||
package telemetry
|
||||
|
||||
import "strconv"
|
||||
|
||||
func EmptyTransform(v any, out *TelemetryField) {
|
||||
out.Type = DataTypeCHAR
|
||||
out.Raw = uint64('-')
|
||||
}
|
||||
|
||||
func UInt8Transform(v int, out *TelemetryField) {
|
||||
out.Type = DataTypeUINT8
|
||||
|
||||
if v < 0 {
|
||||
out.Raw = uint64(0)
|
||||
return
|
||||
}
|
||||
|
||||
out.Raw = uint64(v)
|
||||
}
|
||||
|
||||
func FloatToStringTransform(v float32, out *TelemetryField) {
|
||||
out.Type = DataTypeSTRING
|
||||
|
||||
if v < 0.0 {
|
||||
out.Str = "inv"
|
||||
return
|
||||
}
|
||||
|
||||
out.Str = strconv.FormatFloat(float64(v), 'f', 1, 32)
|
||||
}
|
||||
|
||||
func FloatToUInt8Transform(v float32, out *TelemetryField) {
|
||||
out.Type = DataTypeUINT8
|
||||
|
||||
if v < 0.0 {
|
||||
out.Raw = uint64(0)
|
||||
return
|
||||
}
|
||||
|
||||
out.Raw = uint64(v)
|
||||
}
|
||||
+32
-76
@@ -1,12 +1,18 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
fieldNameToID = make(map[string]FieldID, MaxFields)
|
||||
for id, name := range FieldNames {
|
||||
fieldNameToID[name] = FieldID(id)
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: allow the user to create custom data things. For example, iRacing provides
|
||||
// multiple surface temps, but I guess the user doesn't want all of them at once.
|
||||
// allow him to make something that allows some data transformation to occur.
|
||||
@@ -27,10 +33,11 @@ type VirtualField interface {
|
||||
// NOTE: Update the iracing SDK to write data to the same map ALWAYS, then
|
||||
// I can bind that address and read directly from there on the transform
|
||||
|
||||
// BoundField is the data structure we use to bind the telemetry provider's data
|
||||
// to our internal telemetry fields
|
||||
type BoundField struct {
|
||||
Key string
|
||||
ID FieldID
|
||||
Transform func(any, *TelemetryField)
|
||||
ID FieldID
|
||||
Update func(out *TelemetryField)
|
||||
}
|
||||
|
||||
var bufferPool = sync.Pool{
|
||||
@@ -63,52 +70,15 @@ const (
|
||||
// NOTE: we can optimize this via a special command that says a given piece of data
|
||||
// is for multiple targets
|
||||
type TelemetryField struct {
|
||||
IDs []int16 // Identification for the serial device
|
||||
// IDs []int16 // Identification for the serial device
|
||||
Type DataType
|
||||
Raw uint64
|
||||
Str string // Only to be used with DataTypeSTRING
|
||||
}
|
||||
|
||||
// Pack will pack this current TelemetryField into bytes to send over the wire
|
||||
// Format:
|
||||
// 0x00 - Field ID
|
||||
// 0x00 |
|
||||
// 0x01 - DataType
|
||||
// 0x02 - if its a (u)int8
|
||||
// or
|
||||
// 0x02 - if its a (u)int16 - first byte
|
||||
// 0x02 - if its a (u)int16 - second byte
|
||||
// or
|
||||
// 0x02 - str len max is 255 chars
|
||||
// [0x02] - str
|
||||
func (tf *TelemetryField) Pack(dest []byte) []byte {
|
||||
// NOTE: maybe we can have a pool of these so we don't have to create them here
|
||||
// or whatever
|
||||
for _, id := range tf.IDs {
|
||||
dest = append(dest, uint8(id), uint8(id>>8))
|
||||
dest = append(dest, uint8(tf.Type))
|
||||
|
||||
switch tf.Type {
|
||||
case DataTypeINT8, DataTypeUINT8, DataTypeCHAR:
|
||||
dest = append(dest, uint8(tf.Raw))
|
||||
case DataTypeINT16, DataTypeUINT16:
|
||||
dest = append(dest, uint8(tf.Raw), uint8(tf.Raw>>8))
|
||||
case DataTypeINT32, DataTypeUINT32:
|
||||
dest = append(dest, uint8(tf.Raw), uint8(tf.Raw>>8), uint8(tf.Raw>>16), uint8(tf.Raw>>24))
|
||||
case DataTypeINT64, DataTypeUINT64:
|
||||
dest = append(dest, uint8(tf.Raw), uint8(tf.Raw>>8), uint8(tf.Raw>>16),
|
||||
uint8(tf.Raw>>24), uint8(tf.Raw>>32), uint8(tf.Raw>>40), uint8(tf.Raw>>48),
|
||||
uint8(tf.Raw>>56),
|
||||
)
|
||||
case DataTypeSTRING:
|
||||
l := min(len(tf.Str), math.MaxUint8)
|
||||
|
||||
dest = append(dest, uint8(l))
|
||||
dest = append(dest, tf.Str[:l]...)
|
||||
}
|
||||
}
|
||||
|
||||
return dest
|
||||
func (tf *TelemetryField) Unused() {
|
||||
tf.Type = DataTypeCHAR
|
||||
tf.Raw = uint64('-')
|
||||
}
|
||||
|
||||
func (tf *TelemetryField) String() string {
|
||||
@@ -128,7 +98,7 @@ func (tf *TelemetryField) String() string {
|
||||
return "NaN"
|
||||
}
|
||||
|
||||
type FieldID uint16
|
||||
type FieldID = uint16
|
||||
|
||||
// We use FirstField to start the count on the fields the user can select
|
||||
// the first three will be for internal use
|
||||
@@ -143,6 +113,14 @@ const (
|
||||
WaterTemp
|
||||
// Engine Warnings
|
||||
PitSpeedLimiter
|
||||
// Electrics (dash lights and so on)
|
||||
LeftIndicator
|
||||
RightIndicator
|
||||
Hazards
|
||||
ABSWarningLight
|
||||
ParkingBrakeLight
|
||||
TCLight
|
||||
BatteryLight
|
||||
// Adjustements
|
||||
BrakeBias
|
||||
ABSSetting
|
||||
@@ -191,6 +169,14 @@ var FieldNames = [MaxFields]string{
|
||||
WaterTemp: "Water Temperature",
|
||||
// Engine Warnings
|
||||
PitSpeedLimiter: "Pit Speed Limiter",
|
||||
// Electrics (dash lights and so on)
|
||||
LeftIndicator: "Left Indicator",
|
||||
RightIndicator: "Right Indicator",
|
||||
Hazards: "Hazards",
|
||||
ABSWarningLight: "ABS Dash Light",
|
||||
ParkingBrakeLight: "Parking Brake Dash Light",
|
||||
TCLight: "Traction Control Light",
|
||||
BatteryLight: "Battery Light",
|
||||
// Ajustments
|
||||
BrakeBias: "BrakeBias",
|
||||
ABSSetting: "ABS Control",
|
||||
@@ -236,13 +222,6 @@ func GetFieldName(id FieldID) string {
|
||||
|
||||
var fieldNameToID map[string]FieldID
|
||||
|
||||
func initFieldNamesMap() {
|
||||
fieldNameToID = make(map[string]FieldID, MaxFields)
|
||||
for id, name := range FieldNames {
|
||||
fieldNameToID[name] = FieldID(id)
|
||||
}
|
||||
}
|
||||
|
||||
func GetFieldID(name string) (FieldID, bool) {
|
||||
id, ok := fieldNameToID[name]
|
||||
return id, ok
|
||||
@@ -262,26 +241,3 @@ type TelemetryData struct {
|
||||
func NewTelemetryData() *TelemetryData {
|
||||
return &TelemetryData{}
|
||||
}
|
||||
|
||||
func (td *TelemetryData) Pack() []byte {
|
||||
bufPtr := bufferPool.Get().(*[]byte)
|
||||
buf := (*bufPtr)[:0]
|
||||
|
||||
// for _, bind := range td.ActiveBinds {
|
||||
// buf = td.Values[bind.ID].Pack(buf)
|
||||
// }
|
||||
|
||||
for k := range td.Values {
|
||||
if len(td.Values[k].IDs) > 0 {
|
||||
buf = td.Values[k].Pack(buf)
|
||||
}
|
||||
}
|
||||
|
||||
// We have to copy here because we have to return the buffer
|
||||
result := make([]byte, len(buf))
|
||||
copy(result, buf)
|
||||
|
||||
bufferPool.Put(&buf)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
// Package telemetry is our interface with our data sources
|
||||
package telemetry
|
||||
|
||||
import "time"
|
||||
|
||||
type TelemetryProvider interface {
|
||||
StopStream()
|
||||
Stream() (<-chan TelemetryData, error)
|
||||
Subscribe(map[int16]FieldID)
|
||||
Subscribe([]FieldID)
|
||||
IsAlive(time.Duration) bool
|
||||
Name() string
|
||||
Close()
|
||||
}
|
||||
|
||||
@@ -1,5 +1 @@
|
||||
package telemetry
|
||||
|
||||
func Init() {
|
||||
initFieldNamesMap()
|
||||
}
|
||||
|
||||
+171
-11
@@ -2,13 +2,15 @@ package controllers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"esdi/cdashdisplay"
|
||||
helper "esdi/helpers"
|
||||
"esdi/tui/internal/services"
|
||||
"esdi/devices/cdashdisplay"
|
||||
"esdi/services"
|
||||
"esdi/tui/internal/views"
|
||||
|
||||
helper "esdi/helpers"
|
||||
|
||||
"github.com/gdamore/tcell/v2"
|
||||
"github.com/rivo/tview"
|
||||
)
|
||||
@@ -18,17 +20,22 @@ type LayoutController struct {
|
||||
OnExit func()
|
||||
LayoutToolView *views.LayoutToolView
|
||||
Messages chan string
|
||||
DevService *services.CDashService
|
||||
DevService *services.DeviceService
|
||||
MoveToolState *windowManipState
|
||||
SelectedLayout string // NOTE: This should be a struct to handle its own things
|
||||
// TODO: create a filter to select the layout
|
||||
// filter telemetry provider, then filter vehicle in use and so on
|
||||
}
|
||||
|
||||
func NewLayoutController(base *Controller, service *services.CDashService) *LayoutController {
|
||||
func NewLayoutController(base *Controller, service *services.DeviceService) *LayoutController {
|
||||
lc := &LayoutController{
|
||||
Controller: base,
|
||||
LayoutToolView: views.NewLayoutToolView(),
|
||||
Messages: make(chan string, 10),
|
||||
DevService: service,
|
||||
MoveToolState: &windowManipState{Mode: moveMode},
|
||||
// SelectedLayout: "beamng.yaml",
|
||||
SelectedLayout: "layout.yaml",
|
||||
}
|
||||
|
||||
lc.registerHooks()
|
||||
@@ -56,6 +63,9 @@ func (lc *LayoutController) registerHooks() {
|
||||
case 'm':
|
||||
lc.Messages <- "calling window manipulation tool\n"
|
||||
lc.moveWindow()
|
||||
case 'c':
|
||||
lc.Messages <- "calling change selected layout tool\n"
|
||||
lc.changeSelectedLoadout()
|
||||
case 's':
|
||||
// Save the current layout
|
||||
lc.Messages <- "calling save layout\n"
|
||||
@@ -64,6 +74,10 @@ func (lc *LayoutController) registerHooks() {
|
||||
// Load the layout
|
||||
lc.Messages <- "calling load layout\n"
|
||||
lc.loadLayout()
|
||||
case 'u':
|
||||
// Unload the layout
|
||||
lc.Messages <- "calling unload layout\n"
|
||||
lc.unloadLayout()
|
||||
case 'g':
|
||||
// Go -> launches the current set up source
|
||||
// streamingWindow(bus, doc)
|
||||
@@ -196,7 +210,20 @@ func (lc *LayoutController) createWindow() {
|
||||
return
|
||||
}
|
||||
|
||||
window, err = lc.DevService.CreateWindow(window)
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
// ---
|
||||
|
||||
window, err = display.CreateWindow(window)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to create window\n"
|
||||
return
|
||||
@@ -293,7 +320,20 @@ func (lc *LayoutController) newWindowAction() {
|
||||
}
|
||||
|
||||
func (lc *LayoutController) updateWindowAction(win *cdashdisplay.DesktopUIWindow) {
|
||||
err := lc.DevService.UpdateWindow(win)
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
// ---
|
||||
|
||||
err = display.UpdateWindow(win)
|
||||
|
||||
lc.Messages <- fmt.Sprintf("Window: %v\n", win)
|
||||
|
||||
@@ -306,7 +346,20 @@ func (lc *LayoutController) updateWindowAction(win *cdashdisplay.DesktopUIWindow
|
||||
func (lc *LayoutController) displayLoadedLayouts() {
|
||||
lc.Logger.Debug("We want to view our layout!")
|
||||
|
||||
for _, w := range lc.DevService.CDash.State.Layout.Windows {
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
// ---
|
||||
|
||||
for _, w := range display.State.Layout.Windows {
|
||||
lc.Logger.Debug("==========================================================================")
|
||||
lc.Logger.Debug(fmt.Sprintf("updating form view for a layout: %+v", w.UIData.TelemetryField))
|
||||
err := lc.updateFormView(w)
|
||||
@@ -338,8 +391,21 @@ func (lc *LayoutController) getCurrentTreeNodeModel() (*tview.TreeNode, int16, e
|
||||
}
|
||||
|
||||
func (lc *LayoutController) loadLayout() {
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
// ---
|
||||
|
||||
// We would get the layout path from somewhere but for nots its layout.yaml
|
||||
err := lc.DevService.LoadLayout("layout.yaml")
|
||||
err = display.LoadLayout(lc.SelectedLayout)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to load layout: " + err.Error()
|
||||
return
|
||||
@@ -348,8 +414,42 @@ func (lc *LayoutController) loadLayout() {
|
||||
lc.displayLoadedLayouts()
|
||||
}
|
||||
|
||||
func (lc *LayoutController) unloadLayout() {
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
// ---
|
||||
|
||||
err = display.UnloadLayout()
|
||||
if err != nil {
|
||||
lc.Logger.Error(fmt.Sprintf("Failed to unload layout: %+v", err))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (lc *LayoutController) saveLayout() {
|
||||
err := lc.DevService.SaveLayout("layout.yaml")
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
// ---
|
||||
|
||||
err = display.SaveLayout(lc.SelectedLayout)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to save layout: " + err.Error()
|
||||
return
|
||||
@@ -369,8 +469,21 @@ func (lc *LayoutController) deleteWindow() {
|
||||
}
|
||||
wID := curNode.GetReference().(int16)
|
||||
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return
|
||||
}
|
||||
// ---
|
||||
|
||||
// Delete it
|
||||
err := lc.DevService.DeleteWindow(wID)
|
||||
err = display.DestroyWindow(wID)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to delete window: " + err.Error() + "\n"
|
||||
return
|
||||
@@ -423,3 +536,50 @@ func (lc *LayoutController) moveWindow() {
|
||||
|
||||
lc.App.SetFocus(formView.Form)
|
||||
}
|
||||
|
||||
// changeSelectedLoadout is used to change the currently selected loadout
|
||||
// its a very bare bones utility to aid development
|
||||
// NOTE: FOR THE LOVE OF WHATS HOLY ACTUALLY MAKE THIS GOOD BEFORE ADDING MORE FEATURES
|
||||
func (lc *LayoutController) changeSelectedLoadout() {
|
||||
// First we get the files in the layouts directory
|
||||
entries, err := os.ReadDir("./layouts")
|
||||
if err != nil {
|
||||
lc.Logger.Error(fmt.Sprintf("Failed to read directory: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Then we open a modal and pass that list there
|
||||
lc.Logger.Debug(fmt.Sprintf("Found layouts: %+v", entries))
|
||||
|
||||
layoutSelection := views.NewLayoutToolLayoutsList()
|
||||
layoutSelection.AddEntries(entries)
|
||||
layoutSelection.Tree.SetInputCapture(func(ev *tcell.EventKey) *tcell.EventKey {
|
||||
switch ev.Key() {
|
||||
case tcell.KeyESC:
|
||||
// We have to destroy this window, but first we tell the pages to show something else
|
||||
// NOTE: will this be left hanging and then given to GC? Can we improve that?
|
||||
lc.LayoutToolView.LayoutActions.LayoutSelection = nil
|
||||
lc.LayoutToolView.DeleteLayoutList()
|
||||
lc.App.SetFocus(lc.LayoutToolView.LayoutTree.Tree)
|
||||
}
|
||||
|
||||
return ev
|
||||
})
|
||||
|
||||
layoutSelection.Tree.SetSelectedFunc(func(node *tview.TreeNode) {
|
||||
ref := node.GetReference()
|
||||
if ref == nil {
|
||||
return
|
||||
}
|
||||
|
||||
lc.Messages <- "User selected " + fmt.Sprintf("%+v", ref) + "\n"
|
||||
lc.SelectedLayout = ref.(string)
|
||||
|
||||
lc.LayoutToolView.LayoutTree.Tree.SetTitle(fmt.Sprintf("%s [%s]",
|
||||
views.LayoutToolTreeViewTitle, ref.(string)))
|
||||
})
|
||||
|
||||
lc.LayoutToolView.LayoutActions.LayoutSelection = layoutSelection
|
||||
lc.LayoutToolView.ShowLayoutList()
|
||||
lc.App.SetFocus(lc.LayoutToolView.LayoutActions.LayoutSelection.Tree)
|
||||
}
|
||||
+35
-6
@@ -1,6 +1,7 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"esdi/devices/cdashdisplay"
|
||||
helper "esdi/helpers"
|
||||
|
||||
"github.com/gdamore/tcell/v2"
|
||||
@@ -43,40 +44,68 @@ func keyToVector(r rune) (helper.Vector, bool) {
|
||||
}
|
||||
|
||||
func (lc *LayoutController) handleMovementCapture(idx int16,
|
||||
ev *tcell.EventKey) *tcell.EventKey {
|
||||
ev *tcell.EventKey,
|
||||
) *tcell.EventKey {
|
||||
vec, ok := keyToVector(ev.Rune())
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := lc.DevService.MoveWindow(idx, &vec)
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return nil
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return nil
|
||||
}
|
||||
// ---
|
||||
|
||||
err = display.MoveWindow(idx, &vec)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to move window: " + err.Error() + "\n"
|
||||
return nil
|
||||
}
|
||||
|
||||
// Success - update the form
|
||||
window := lc.DevService.CDash.State.Layout.Windows[idx]
|
||||
window := display.State.Layout.Windows[idx]
|
||||
lc.LayoutToolView.UpdateFormView(idx, window)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (lc *LayoutController) handleResizeCapture(idx int16,
|
||||
ev *tcell.EventKey) *tcell.EventKey {
|
||||
ev *tcell.EventKey,
|
||||
) *tcell.EventKey {
|
||||
vec, ok := keyToVector(ev.Rune())
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := lc.DevService.ResizeWindow(idx, &vec)
|
||||
// Acquire the cdashdisplay
|
||||
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to get " + cdashdisplay.NAME
|
||||
return nil
|
||||
}
|
||||
display, ok := displayIF.(*cdashdisplay.CDashDisplay)
|
||||
if !ok {
|
||||
lc.Messages <- "failed to acquire " + cdashdisplay.NAME
|
||||
return nil
|
||||
}
|
||||
// ---
|
||||
|
||||
err = display.ResizeWindow(idx, &vec)
|
||||
if err != nil {
|
||||
lc.Messages <- "failed to resize window: " + err.Error() + "\n"
|
||||
return nil
|
||||
}
|
||||
|
||||
// Success - update the form
|
||||
window := lc.DevService.CDash.State.Layout.Windows[idx]
|
||||
window := display.State.Layout.Windows[idx]
|
||||
lc.LayoutToolView.UpdateFormView(idx, window)
|
||||
|
||||
return nil
|
||||
@@ -24,6 +24,9 @@ func ListFormButtonLabels(form *tview.Form) []string {
|
||||
}
|
||||
|
||||
func SetFormButtonCallback(form *tview.Form, btnLabel string, fn func()) error {
|
||||
// NOTE: is there a better way to do this ???
|
||||
// Find out
|
||||
|
||||
btnIndex := form.GetButtonIndex(btnLabel)
|
||||
if btnIndex == -1 {
|
||||
availableButtons := ListFormButtonLabels(form)
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
serv "esdi/tui/internal/services"
|
||||
"esdi/tui/internal/views"
|
||||
"fmt"
|
||||
|
||||
"esdi/devices/cdashdisplay"
|
||||
serv "esdi/services"
|
||||
"esdi/tui/internal/views"
|
||||
|
||||
"github.com/gdamore/tcell/v2"
|
||||
)
|
||||
|
||||
@@ -14,12 +16,12 @@ type DeviceController struct {
|
||||
DeviceAPIView *views.DeviceAPIView
|
||||
LayoutCtrl *LayoutController
|
||||
StreamCtrl *StreamingCtrl
|
||||
DevService *serv.CDashService
|
||||
DevService *serv.DeviceService
|
||||
}
|
||||
|
||||
func NewDeviceController(
|
||||
base *Controller,
|
||||
devService *serv.CDashService,
|
||||
devService *serv.DeviceService,
|
||||
telemService *serv.TelemetryService,
|
||||
) *DeviceController {
|
||||
mc := &DeviceController{
|
||||
@@ -55,7 +57,7 @@ func (mc *DeviceController) setDeviceAPIViewEvents() {
|
||||
SetInputCapture(func(ev *tcell.EventKey) *tcell.EventKey {
|
||||
switch ev.Rune() {
|
||||
case 'r':
|
||||
go mc.DevService.FindDevice()
|
||||
go mc.DevService.FindDevices()
|
||||
}
|
||||
return ev
|
||||
})
|
||||
@@ -64,6 +66,12 @@ func (mc *DeviceController) setDeviceAPIViewEvents() {
|
||||
func (mc *DeviceController) AddDeviceAPIListItems() {
|
||||
mc.DeviceAPIView.DevAPIList.
|
||||
AddItem("layout", "build a layout for CDashDisplay", func() {
|
||||
// This CDashDisplay specific, only load if we have a CDashDisplay
|
||||
if !mc.DevService.DeviceExists(cdashdisplay.NAME) {
|
||||
mc.DevService.Messages <- "CDashDisplay it not loaded yet\n"
|
||||
return
|
||||
}
|
||||
|
||||
// Get the api pages
|
||||
views.AddAndShowPage(
|
||||
mc.DeviceAPIView.DevAPIToolView.Pages,
|
||||
@@ -74,14 +82,21 @@ func (mc *DeviceController) AddDeviceAPIListItems() {
|
||||
})
|
||||
mc.DeviceAPIView.DevAPIList.
|
||||
AddItem("stream", "stream data to the display", func() {
|
||||
views.AddAndShowPage(mc.DeviceAPIView.DevAPIToolView.Pages,
|
||||
// If we don't have a CDashDisplay or data source, this should be blocked
|
||||
if !mc.StreamCtrl.TelemServ.HasActiveProvider() {
|
||||
mc.StreamCtrl.Messages <- "no active provider present\n"
|
||||
return
|
||||
}
|
||||
|
||||
views.AddAndShowPage(
|
||||
mc.DeviceAPIView.DevAPIToolView.Pages,
|
||||
"streaming-tool",
|
||||
mc.StreamCtrl.StreamView.TextView,
|
||||
mc.StreamCtrl.StreamView.Flex,
|
||||
)
|
||||
|
||||
mc.StreamCtrl.SetInternalState()
|
||||
|
||||
mc.App.SetFocus(mc.StreamCtrl.StreamView.TextView)
|
||||
mc.App.SetFocus(mc.StreamCtrl.StreamView.Options.Form)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,41 +1,57 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"esdi/telemetry"
|
||||
"esdi/tui/internal/services"
|
||||
"esdi/tui/internal/views"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
|
||||
"esdi/config"
|
||||
"esdi/devices/uidevice"
|
||||
"esdi/providers"
|
||||
"esdi/services"
|
||||
"esdi/telemetry"
|
||||
"esdi/tui/internal/models"
|
||||
"esdi/tui/internal/views"
|
||||
|
||||
"github.com/gdamore/tcell/v2"
|
||||
)
|
||||
|
||||
type StreamingCtrl struct {
|
||||
*Controller
|
||||
Service *services.CDashService
|
||||
StreamView *views.StreamView
|
||||
Messages chan string
|
||||
Internal chan string
|
||||
Run bool
|
||||
OnExit func()
|
||||
isRunning bool
|
||||
TelemServ *services.TelemetryService
|
||||
DevService *services.DeviceService
|
||||
StreamView *views.StreamToolView
|
||||
Messages chan string
|
||||
Internal chan string
|
||||
TelemetryCh <-chan telemetry.TelemetryData
|
||||
Run bool
|
||||
OnExit func()
|
||||
TelemServ *services.TelemetryService
|
||||
|
||||
// Stream State
|
||||
isRunning bool
|
||||
}
|
||||
|
||||
func NewStreamingCtrl(
|
||||
base *Controller,
|
||||
serCDash *services.CDashService,
|
||||
devService *services.DeviceService,
|
||||
serTelem *services.TelemetryService,
|
||||
) *StreamingCtrl {
|
||||
// NOTE: looks sus, put this somewhere also. Not very good in here
|
||||
providerList := []providers.Provider{}
|
||||
for _, item := range providers.Providers {
|
||||
providerList = append(providerList, item)
|
||||
}
|
||||
streamView := views.NewStreamToolView(providerList, config.GetCfg().DefaultSim)
|
||||
|
||||
ctrl := &StreamingCtrl{
|
||||
Controller: base,
|
||||
Service: serCDash,
|
||||
TelemServ: serTelem,
|
||||
Messages: make(chan string, 10),
|
||||
Internal: make(chan string, 10),
|
||||
Run: false,
|
||||
StreamView: views.NewStreamView(),
|
||||
isRunning: false,
|
||||
Controller: base,
|
||||
DevService: devService,
|
||||
TelemServ: serTelem,
|
||||
Messages: make(chan string, 10),
|
||||
Internal: make(chan string, 10),
|
||||
TelemetryCh: make(chan telemetry.TelemetryData, 1),
|
||||
Run: false,
|
||||
StreamView: streamView,
|
||||
}
|
||||
|
||||
ctrl.registerHooks()
|
||||
@@ -43,8 +59,13 @@ func NewStreamingCtrl(
|
||||
return ctrl
|
||||
}
|
||||
|
||||
// func (sc *StreamingCtrl) subscribeListeners() {
|
||||
// // Here I will set a UIDevice
|
||||
// sc.TelemetryCh = sc.TelemServ.SubscribeListener("UI", 1)
|
||||
// }
|
||||
|
||||
func (sc *StreamingCtrl) registerHooks() {
|
||||
sc.StreamView.TextView.SetInputCapture(func(ev *tcell.EventKey) *tcell.EventKey {
|
||||
sc.StreamView.Options.Form.SetInputCapture(func(ev *tcell.EventKey) *tcell.EventKey {
|
||||
switch ev.Key() {
|
||||
case tcell.KeyEsc:
|
||||
sc.OnExit()
|
||||
@@ -52,36 +73,82 @@ func (sc *StreamingCtrl) registerHooks() {
|
||||
|
||||
switch ev.Rune() {
|
||||
case 's':
|
||||
// Start
|
||||
sc.Start()
|
||||
case 'p':
|
||||
// Pause
|
||||
// sc.Stop()
|
||||
// Start - stop
|
||||
sc.StartStop()
|
||||
case 'u':
|
||||
// Update
|
||||
sc.updateStream()
|
||||
}
|
||||
|
||||
return ev
|
||||
})
|
||||
|
||||
// Set the options form callbacks
|
||||
err := SetFormButtonCallback(sc.StreamView.Options.Form, "Update", func() {
|
||||
sc.updateStream()
|
||||
})
|
||||
if err != nil {
|
||||
// NOTE: what do we do here?
|
||||
panic("Failed to set callback for streaming controller form update button")
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *StreamingCtrl) Start() {
|
||||
stream := sc.TelemServ.StartStream()
|
||||
func (sc *StreamingCtrl) StartStop() {
|
||||
if sc.TelemServ.IsStreaming() {
|
||||
slog.Info("stopping stream")
|
||||
|
||||
var isDrawing atomic.Bool
|
||||
sc.TelemServ.StopStream()
|
||||
sc.DevService.StopStream()
|
||||
|
||||
go func() {
|
||||
for msg := range stream {
|
||||
if isDrawing.Load() {
|
||||
continue
|
||||
}
|
||||
sc.isRunning = false
|
||||
return
|
||||
}
|
||||
|
||||
isDrawing.Store(true)
|
||||
// stream is not running, we have to start it now
|
||||
// NOTE:
|
||||
// Subscribe the only existing device - needs to be discovered by now
|
||||
slog.Debug("setting the data stream for device servie")
|
||||
sc.DevService.SetTelemetryChannel(sc.TelemServ.SubscribeListener("DeviceService", 1))
|
||||
|
||||
sc.App.QueueUpdateDraw(func() {
|
||||
sc.StreamView.Update(&msg)
|
||||
isDrawing.Store(false)
|
||||
})
|
||||
dev, err := sc.DevService.GetDevice(uidevice.NAME)
|
||||
if err == nil {
|
||||
if uiDev, ok := dev.(*uidevice.UIDevice); ok {
|
||||
sc.TelemetryCh = uiDev.DataChannel()
|
||||
go sc.listenToUIStream()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
slog.Debug("starting services")
|
||||
sc.DevService.StartStream()
|
||||
sc.TelemServ.StartStream()
|
||||
|
||||
sc.isRunning = true
|
||||
|
||||
slog.Debug("starting stream")
|
||||
}
|
||||
|
||||
func (sc *StreamingCtrl) parseStreamUpdateForm(form *views.StreamOptionsView) (*models.StreamOptions, error) {
|
||||
_, sim := form.SimDropdown.GetCurrentOption()
|
||||
|
||||
return &models.StreamOptions{
|
||||
Sim: sim,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// updateStream will get the new options from the form and update the state accordingly
|
||||
func (sc *StreamingCtrl) updateStream() {
|
||||
sc.Messages <- "Request to update stream received - parsing form"
|
||||
|
||||
formData, err := sc.parseStreamUpdateForm(sc.StreamView.Options)
|
||||
if err != nil {
|
||||
slog.Error(fmt.Sprintf("failed to parse form data: %+v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// NOTE: find a way to hold state so we can compare this new state to the old
|
||||
// state. Need a streamctrl state that holds the form model, for example
|
||||
|
||||
slog.Debug(fmt.Sprintf("Parsed form data: %+v", formData))
|
||||
}
|
||||
|
||||
// SetInternalState is used to update the stuff in here, for example, the user
|
||||
@@ -92,14 +159,28 @@ func (sc *StreamingCtrl) Start() {
|
||||
// Performance reasoning: this is not used during the high frequency data transmission
|
||||
// so we can get away with using a map for convenience here
|
||||
func (sc *StreamingCtrl) SetInternalState() {
|
||||
fields := make(map[int16]telemetry.FieldID, len(sc.Service.CDash.State.Layout.Windows))
|
||||
fields := sc.TelemServ.SubscribeToFields()
|
||||
|
||||
for _, w := range sc.Service.CDash.State.Layout.Windows {
|
||||
fieldID, _ := telemetry.GetFieldID(w.UIData.TelemetryField)
|
||||
fields[w.UIData.IDX] = fieldID
|
||||
}
|
||||
// sc.Messages <- fmt.Sprintf("Subscribed Fields: %+v [%d]\n", fields, len(fields))
|
||||
// Should I update this?
|
||||
sc.Messages <- fmt.Sprintf("Subscribed to fields: %+v", fields)
|
||||
}
|
||||
|
||||
func (sc *StreamingCtrl) listenToUIStream() {
|
||||
var isDrawing atomic.Bool
|
||||
|
||||
for msg := range sc.TelemetryCh {
|
||||
if isDrawing.Load() {
|
||||
continue
|
||||
}
|
||||
isDrawing.Store(true)
|
||||
|
||||
sc.TelemServ.ActiveProvider.Subscribe(fields)
|
||||
// Capture locally
|
||||
telemetryMsg := msg
|
||||
|
||||
sc.Messages <- fmt.Sprintf("Subscribed Fields: %+v [%d]\n", fields, len(fields))
|
||||
sc.App.QueueUpdateDraw(func() {
|
||||
sc.StreamView.Visualizer.Update(&telemetryMsg)
|
||||
isDrawing.Store(false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package models
|
||||
|
||||
type StreamOptions struct {
|
||||
Sim string
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"esdi/cdashdisplay"
|
||||
helper "esdi/helpers"
|
||||
"esdi/peripheral"
|
||||
"esdi/telemetry"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type CDashService struct {
|
||||
Logger *slog.Logger
|
||||
CDash *cdashdisplay.CDashDisplay
|
||||
// iRacingTelemetry *IRacingService
|
||||
DevClerk *peripheral.PeripheralDeviceClerk
|
||||
Messages chan string
|
||||
}
|
||||
|
||||
func NewCDashService(logger *slog.Logger) *CDashService {
|
||||
sharedChannel := make(chan string, 10)
|
||||
return &CDashService{
|
||||
Logger: logger,
|
||||
CDash: nil,
|
||||
DevClerk: peripheral.NewPeripheralDeviceClerk(),
|
||||
Messages: sharedChannel,
|
||||
}
|
||||
}
|
||||
|
||||
func (cds *CDashService) FindDevice() {
|
||||
cds.Messages <- "looking for cdash display...\n"
|
||||
cds.Logger.Info("Looking for CDashDisplay")
|
||||
|
||||
cdashdisplay.SetLogger(cds.Logger.With("[device]", "cdashdisplay"))
|
||||
|
||||
display, err := cdashdisplay.NewCDashDisplay()
|
||||
if err != nil {
|
||||
cds.Logger.Info("didn't find cdashdisplay")
|
||||
cds.Messages <- "didn't find cdash display\n"
|
||||
return
|
||||
}
|
||||
|
||||
cds.CDash = display
|
||||
cds.Logger.Info("found cdashdisplay on: " + display.WT.Cfg.Name)
|
||||
cds.Messages <- "found cdashdisplay on: " + display.WT.Cfg.Name + "\n"
|
||||
}
|
||||
|
||||
func (cds *CDashService) CreateWindow(
|
||||
win *cdashdisplay.DesktopUIWindow,
|
||||
) (*cdashdisplay.DesktopUIWindow, error) {
|
||||
updatedWindow, err := cds.CDash.CreateWindow(win)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return updatedWindow, nil
|
||||
}
|
||||
|
||||
func (cds *CDashService) LoadLayout(layoutPath string) error {
|
||||
return cds.CDash.LoadLayout(layoutPath)
|
||||
}
|
||||
|
||||
func (cds *CDashService) SaveLayout(layoutPath string) error {
|
||||
return cds.CDash.SaveLayout(layoutPath)
|
||||
}
|
||||
|
||||
func (cds *CDashService) UpdateWindow(win *cdashdisplay.DesktopUIWindow) error {
|
||||
cds.Messages <- fmt.Sprintf("Updating a window:\n%+v\n", win)
|
||||
return cds.CDash.UpdateWindow(win)
|
||||
}
|
||||
|
||||
func (cds *CDashService) DeleteWindow(idx int16) error {
|
||||
return cds.CDash.DestroyWindow(idx)
|
||||
}
|
||||
|
||||
func (cds *CDashService) ResizeWindow(idx int16, vec *helper.Vector) error {
|
||||
err := cds.CDash.ResizeWindow(idx, vec)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cds *CDashService) MoveWindow(idx int16, vec *helper.Vector) error {
|
||||
err := cds.CDash.MoveWindow(idx, vec)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cds *CDashService) StreamData(stream <-chan telemetry.TelemetryData) {
|
||||
var isSending atomic.Bool
|
||||
|
||||
go func() {
|
||||
for msg := range stream {
|
||||
if isSending.Load() {
|
||||
continue
|
||||
}
|
||||
|
||||
isSending.Store(true)
|
||||
|
||||
cds.CDash.SendData(&msg)
|
||||
isSending.Store(false)
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package services
|
||||
|
||||
// DeviceService will handle sending the data from the telemetry service to the
|
||||
// actual devices
|
||||
// NOTE: create a virtual device and make it be the output window or something so
|
||||
// we can just add it as a device or whatever instead of being a custom made thing
|
||||
// that would be pretty cool I think
|
||||
type DeviceService struct {
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
providerir "esdi/providers/iracing"
|
||||
"log/slog"
|
||||
|
||||
telemetry "esdi/telemetry"
|
||||
)
|
||||
|
||||
// TelemetryService will be our base struct to handle telemetry data
|
||||
// It should hook to a data sink and handle it like iRacing, BeamNG, AC and so on
|
||||
type TelemetryService struct {
|
||||
logger *slog.Logger
|
||||
cdash *CDashService
|
||||
ActiveProvider telemetry.TelemetryProvider
|
||||
}
|
||||
|
||||
func NewTelemetryService(logger *slog.Logger, cdash *CDashService) *TelemetryService {
|
||||
return &TelemetryService{
|
||||
logger: logger,
|
||||
cdash: cdash,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TelemetryService) setIRacingProvider() {
|
||||
path := "/home/esilva/Desktop/projetos/simracing_peripherals/testTelemetry/gt3_mustang_bathurst.ibt"
|
||||
provider, _ := providerir.NewIRacingProvider(t.logger, path, "", "")
|
||||
|
||||
t.ActiveProvider = provider
|
||||
}
|
||||
|
||||
func (t *TelemetryService) SetProvider(provider string) *TelemetryService {
|
||||
if t.ActiveProvider != nil {
|
||||
// Gotta do something here to clean up before switching
|
||||
}
|
||||
|
||||
switch provider {
|
||||
case "iRacing":
|
||||
// Set up iRacing
|
||||
t.setIRacingProvider()
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *TelemetryService) StartStream() <-chan telemetry.TelemetryData {
|
||||
stream, _ := t.ActiveProvider.Stream()
|
||||
|
||||
// Somewhere around here we have to tell the device service to also send data
|
||||
t.cdash.StreamData(stream)
|
||||
|
||||
return stream
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package tviewhelpers
|
||||
|
||||
import "github.com/rivo/tview"
|
||||
|
||||
func FindNodeByID(node *tview.TreeNode, id int16) *tview.TreeNode {
|
||||
if node == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if ref, ok := node.GetReference().(int16); ok {
|
||||
if ref == id {
|
||||
return node
|
||||
}
|
||||
}
|
||||
|
||||
for _, child := range node.GetChildren() {
|
||||
if found := FindNodeByID(child, id); found != nil {
|
||||
return found
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// Package ui
|
||||
package ui
|
||||
|
||||
import "github.com/rivo/tview"
|
||||
|
||||
type UIContext struct {
|
||||
Redraw func()
|
||||
Log func(formatter string, args ...any)
|
||||
ChangeFocus func(p tview.Primitive)
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"esdi/cdashdisplay"
|
||||
helper "esdi/helpers"
|
||||
"esdi/tui/internal/models"
|
||||
|
||||
"github.com/rivo/tview"
|
||||
)
|
||||
|
||||
//
|
||||
|
||||
type TUILoaded struct{}
|
||||
|
||||
//
|
||||
|
||||
// Main controller events
|
||||
|
||||
// Find a way to remove this
|
||||
type ForceRedraw struct{}
|
||||
|
||||
type LogEv struct {
|
||||
Log string
|
||||
}
|
||||
|
||||
type PrintLogEv struct {
|
||||
Log string
|
||||
}
|
||||
|
||||
type RedrawEv struct {
|
||||
Fn func()
|
||||
}
|
||||
|
||||
type ChangeFocusEv struct {
|
||||
Target tview.Primitive
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
// Layout events
|
||||
|
||||
type SaveLayoutEv struct{}
|
||||
type LoadLayoutEv struct{}
|
||||
type RegisterLoadedLayout struct {
|
||||
Layout cdashdisplay.LayoutTree
|
||||
}
|
||||
|
||||
type UpdateWindowEv struct {
|
||||
ID int16
|
||||
Window models.WindowForm
|
||||
}
|
||||
|
||||
type CreateWindowEv struct {
|
||||
Window models.WindowForm
|
||||
}
|
||||
|
||||
type DestroyWindowEv struct {
|
||||
ID int16
|
||||
}
|
||||
|
||||
type LayoutRegisterWindowEv struct {
|
||||
Window models.WindowForm
|
||||
}
|
||||
|
||||
type MoveWindowEv struct {
|
||||
WindowID int16
|
||||
Delta helper.Vector
|
||||
}
|
||||
|
||||
type ResizeWindowEv struct {
|
||||
WindowID int16
|
||||
Delta helper.Vector
|
||||
}
|
||||
|
||||
type WindowCreatedEv struct {
|
||||
ID int16
|
||||
Win cdashdisplay.CDashWin
|
||||
}
|
||||
|
||||
type WindowMovedEv struct {
|
||||
ID int16
|
||||
Dims cdashdisplay.UIDimensions
|
||||
}
|
||||
|
||||
type WindowDestroyedEv struct {
|
||||
ID int16
|
||||
}
|
||||
|
||||
type ErrorCreateWindowEv struct {
|
||||
Error error
|
||||
}
|
||||
|
||||
type ErrorFormParseEv struct {
|
||||
Error error
|
||||
}
|
||||
|
||||
// Layout events --------------------------------------------------------------
|
||||
|
||||
// Device events
|
||||
|
||||
type FindCDashDisplay struct{}
|
||||
|
||||
// Device events --------------------------------------------------------------
|
||||
|
||||
// + Stream events ------------------------------------------------------------
|
||||
|
||||
type StartStreamingReqEv struct{}
|
||||
type StopStreamingReqEv struct{}
|
||||
|
||||
type StreamDataEv struct {
|
||||
Str string
|
||||
}
|
||||
|
||||
// - Stream events ------------------------------------------------------------
|
||||
@@ -4,39 +4,21 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"esdi/cdashdisplay"
|
||||
"esdi/devices/cdashdisplay"
|
||||
tviewh "esdi/tui/internal/tview_helpers"
|
||||
|
||||
"github.com/gdamore/tcell/v2"
|
||||
"github.com/rivo/tview"
|
||||
)
|
||||
|
||||
const (
|
||||
LayoutToolTreeViewTitle = "Layout Tree"
|
||||
LayoutToolFlexID = "layout-tool-flex"
|
||||
LayoutToolTreeID = "layout-tool-tree"
|
||||
LayoutToolActionPagesID = "layout-tool-action-pages"
|
||||
LayoutToolNewWindowID = "new-window-action-form"
|
||||
)
|
||||
|
||||
func FindNodeByID(node *tview.TreeNode, id int16) *tview.TreeNode {
|
||||
if node == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if ref, ok := node.GetReference().(int16); ok {
|
||||
if ref == id {
|
||||
return node
|
||||
}
|
||||
}
|
||||
|
||||
for _, child := range node.GetChildren() {
|
||||
if found := FindNodeByID(child, id); found != nil {
|
||||
return found
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type LayoutTreeView struct {
|
||||
Tree *tview.TreeView
|
||||
InputCapture func(*tcell.EventKey) *tcell.EventKey
|
||||
@@ -49,7 +31,7 @@ func NewLayoutTreeView() *LayoutTreeView {
|
||||
|
||||
view.Tree = tview.NewTreeView()
|
||||
|
||||
view.Tree.SetBorder(true).SetTitle("Layout Tree")
|
||||
view.Tree.SetBorder(true).SetTitle(LayoutToolTreeViewTitle)
|
||||
view.Tree.SetInputCapture(view.InputCapture)
|
||||
// Inject ChangedFunc
|
||||
// Inject SelectedFunc
|
||||
@@ -80,6 +62,7 @@ func (lt *LayoutTreeView) AddWindow(win *cdashdisplay.DesktopUIWindow) error {
|
||||
type LayoutToolActionView struct {
|
||||
Pages *tview.Pages
|
||||
CreateWindowView *CreateWindowFormView
|
||||
LayoutSelection *LayoutToolLayoutsList
|
||||
}
|
||||
|
||||
func NewLayoutToolActionView() *LayoutToolActionView {
|
||||
@@ -173,6 +156,18 @@ func (ltv *LayoutToolView) ShowWindowFormByID(idx int16) {
|
||||
)
|
||||
}
|
||||
|
||||
func (ltv *LayoutToolView) ShowLayoutList() {
|
||||
AddAndShowPage(
|
||||
ltv.LayoutActions.Pages,
|
||||
"available-layouts-list",
|
||||
ltv.LayoutActions.LayoutSelection.Tree,
|
||||
)
|
||||
}
|
||||
|
||||
func (ltv *LayoutToolView) DeleteLayoutList() {
|
||||
ltv.LayoutActions.Pages.RemovePage("available-layouts-list")
|
||||
}
|
||||
|
||||
func (ltv *LayoutToolView) DeleteWindowByNode(node *tview.TreeNode) {
|
||||
root := ltv.LayoutTree.Tree.GetRoot()
|
||||
if root == nil {
|
||||
@@ -199,7 +194,7 @@ func (ltv *LayoutToolView) UpdateFormView(idx int16, win *cdashdisplay.DesktopUI
|
||||
return
|
||||
}
|
||||
|
||||
node := FindNodeByID(root, idx)
|
||||
node := tviewh.FindNodeByID(root, idx)
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package views
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"esdi/cdashdisplay"
|
||||
"esdi/devices/cdashdisplay"
|
||||
"esdi/telemetry"
|
||||
|
||||
"github.com/rivo/tview"
|
||||
@@ -87,6 +87,7 @@ func NewCreateWindowFormView() *CreateWindowFormView {
|
||||
Form: NewCDashDisplayWindowFormView(),
|
||||
}
|
||||
|
||||
// NOTE: is this variable actually used anywhere
|
||||
view.CreateBtn = tview.NewButton("Create")
|
||||
// Need to inject the button functionality later
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package views
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/rivo/tview"
|
||||
)
|
||||
|
||||
type LayoutToolLayoutsList struct {
|
||||
Tree *tview.TreeView
|
||||
}
|
||||
|
||||
func NewLayoutToolLayoutsList() *LayoutToolLayoutsList {
|
||||
view := &LayoutToolLayoutsList{}
|
||||
|
||||
view.Tree = tview.NewTreeView()
|
||||
|
||||
view.Tree.SetBorder(true).SetTitle("Layout List")
|
||||
// Inject InputCapture
|
||||
// Inject ChangedFunc
|
||||
// Inject SelectedFunc
|
||||
|
||||
// Create a root element
|
||||
rootElem := tview.NewTreeNode(".")
|
||||
view.Tree.SetRoot(rootElem).SetCurrentNode(rootElem)
|
||||
|
||||
return view
|
||||
}
|
||||
|
||||
// AddEntries adds the list of files we wish the user to select from
|
||||
// For now we will send just a list of []string but in the future this should
|
||||
// receive (or have an alternative to receive) a directory structure
|
||||
func (ltll *LayoutToolLayoutsList) AddEntries(entries []os.DirEntry) {
|
||||
root := ltll.Tree.GetRoot()
|
||||
if root == nil {
|
||||
// NOTE: shouldn't happen at all
|
||||
return
|
||||
}
|
||||
|
||||
for _, e := range entries {
|
||||
node := tview.NewTreeNode(e.Name()).
|
||||
SetReference(e.Name())
|
||||
root.AddChild(node)
|
||||
}
|
||||
}
|
||||
@@ -51,9 +51,6 @@ type DeviceAPIListView struct {
|
||||
|
||||
func NewDeviceAPIListView() *DeviceAPIListView {
|
||||
deviceAPIList := tview.NewList()
|
||||
// AddItem("layout", "build a layout for CDashDisplay", 0, func() {
|
||||
// layoutToolUIOnSelect(bus, doc)
|
||||
// })
|
||||
deviceAPIList.SetBorder(true).SetTitle("list")
|
||||
|
||||
return &DeviceAPIListView{
|
||||
@@ -75,40 +72,18 @@ func (dl *DeviceAPIListView) AddItem(name, description string, onSelect func())
|
||||
}
|
||||
|
||||
func NewDeviceAPIView() (*DeviceAPIView, error) {
|
||||
// To build the main view we must set the DOM root
|
||||
mainFlex := tview.NewFlex().SetDirection(tview.FlexColumn)
|
||||
// mainFlexUINode, err := doc.NewUINode(MainFlexID, nil, mainFlex)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
//
|
||||
// doc.SetRoot(mainFlexUINode)
|
||||
|
||||
deviceAPIList := NewDeviceAPIListView()
|
||||
// apiListWindowUINode, err := doc.NewUINode(DeviceAPIListID, doc.GetRootElem(),
|
||||
// deviceAPIList.List)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
|
||||
apiToolPages := NewDeviceAPIToolView()
|
||||
// apiToolPagesNode, err := doc.NewUINode(APIToolPagesID, doc.GetElemByID(RightFlexID),
|
||||
// apiToolPages.Pages)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
|
||||
mainFlex.
|
||||
AddItem(deviceAPIList.List, 0, 1, false).
|
||||
AddItem(apiToolPages.Pages, 0, 4, false)
|
||||
|
||||
// Output window
|
||||
|
||||
outputWin := NewOutputWinView()
|
||||
// _, err = doc.NewUINode("output-window", nil, outputWin.TextArea)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
|
||||
// Flex with debug window
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package views
|
||||
|
||||
import (
|
||||
telem "esdi/telemetry"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"esdi/providers"
|
||||
telem "esdi/telemetry"
|
||||
|
||||
"github.com/rivo/tview"
|
||||
)
|
||||
|
||||
@@ -17,20 +19,58 @@ const (
|
||||
BrakeBiasLen = 6
|
||||
)
|
||||
|
||||
type StreamView struct {
|
||||
// Form to select the game and whatnot ↓↓↓↓
|
||||
|
||||
// StreamOptionsView will be our view element to show the stream data
|
||||
type StreamOptionsView struct {
|
||||
Form *tview.Form
|
||||
SimDropdown *tview.DropDown
|
||||
UpdateBtn *tview.Button
|
||||
}
|
||||
|
||||
func NewStreamOptionsView(providerList []providers.Provider, defaultProvider string,
|
||||
) *StreamOptionsView {
|
||||
sov := &StreamOptionsView{}
|
||||
|
||||
sov.Form = tview.NewForm()
|
||||
sov.Form.SetTitle("Stream Options").SetBorder(true)
|
||||
|
||||
defaultIdx := 0
|
||||
sov.SimDropdown = tview.NewDropDown().SetLabel("SIM").SetCurrentOption(0)
|
||||
for k, prov := range providerList {
|
||||
sov.SimDropdown.AddOption(prov.Name, func() {})
|
||||
|
||||
if prov.Name == defaultProvider {
|
||||
defaultIdx = k
|
||||
}
|
||||
}
|
||||
sov.SimDropdown.SetCurrentOption(defaultIdx)
|
||||
sov.Form.AddFormItem(sov.SimDropdown)
|
||||
|
||||
// Inject callback on the controller
|
||||
sov.Form.AddButton("Update", func() {})
|
||||
|
||||
return sov
|
||||
}
|
||||
|
||||
// Form to select the game and whatnot ↑↑↑↑
|
||||
|
||||
// Area to visualize what data is being passed to the game and whatnot ↓↓↓↓
|
||||
|
||||
type StreamVisualizerView struct {
|
||||
TextView *tview.TextView
|
||||
}
|
||||
|
||||
func NewStreamView() *StreamView {
|
||||
func NewStreamVisualizerView() *StreamVisualizerView {
|
||||
tv := tview.NewTextView()
|
||||
tv.SetTitle("Streaming Tool").SetBorder(true)
|
||||
tv.SetTitle("Streaming Visualizer").SetBorder(true)
|
||||
|
||||
return &StreamView{
|
||||
return &StreamVisualizerView{
|
||||
TextView: tv,
|
||||
}
|
||||
}
|
||||
|
||||
func (sv *StreamView) Update(data *telem.TelemetryData) {
|
||||
func (sv *StreamVisualizerView) Update(data *telem.TelemetryData) {
|
||||
sv.TextView.SetText(stringify(data))
|
||||
}
|
||||
|
||||
@@ -49,3 +89,32 @@ func stringify(data *telem.TelemetryData) string {
|
||||
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
// Area to visualize what data is being passed to the game and whatnot ↑↑↑↑
|
||||
|
||||
// Stream Tool ↓↓↓↓
|
||||
|
||||
type StreamToolView struct {
|
||||
Flex *tview.Flex
|
||||
Options *StreamOptionsView
|
||||
Visualizer *StreamVisualizerView
|
||||
}
|
||||
|
||||
func NewStreamToolView(providerList []providers.Provider, defaultProvider string) *StreamToolView {
|
||||
optionsView := NewStreamOptionsView(providerList, defaultProvider)
|
||||
visualizerView := NewStreamVisualizerView()
|
||||
flex := tview.NewFlex().SetDirection(tview.FlexColumn)
|
||||
flex.SetTitle("Streaming Tool")
|
||||
|
||||
flex.
|
||||
AddItem(optionsView.Form, 0, 2, true).
|
||||
AddItem(visualizerView.TextView, 0, 5, true)
|
||||
|
||||
return &StreamToolView{
|
||||
Flex: flex,
|
||||
Options: optionsView,
|
||||
Visualizer: visualizerView,
|
||||
}
|
||||
}
|
||||
|
||||
// Stream Tool ↑↑↑↑
|
||||
|
||||
+10
-5
@@ -2,10 +2,11 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"esdi/tui/internal/controllers"
|
||||
"esdi/tui/internal/services"
|
||||
"log/slog"
|
||||
|
||||
"esdi/services"
|
||||
"esdi/tui/internal/controllers"
|
||||
|
||||
"github.com/rivo/tview"
|
||||
)
|
||||
|
||||
@@ -16,18 +17,22 @@ type ControlPanel struct {
|
||||
}
|
||||
|
||||
func NewControlPanel(logger *slog.Logger) *ControlPanel {
|
||||
// NOTE: given the services should not be only for the TUI should this be here?
|
||||
baseController := &controllers.Controller{
|
||||
Logger: logger,
|
||||
App: tview.NewApplication(),
|
||||
}
|
||||
|
||||
devService := services.NewCDashService(logger)
|
||||
telemService := services.NewTelemetryService(logger, devService).
|
||||
SetProvider("iRacing")
|
||||
// NOTE: create our device service here
|
||||
devService := services.NewDeviceService(logger.With("service", "DeviceService"))
|
||||
|
||||
telemService := services.NewTelemetryService(logger, devService)
|
||||
if telemService == nil {
|
||||
panic("failed to create the telemetry service")
|
||||
}
|
||||
|
||||
go telemService.FindProvider(telemService.CtxMonitor)
|
||||
|
||||
return &ControlPanel{
|
||||
Controller: baseController,
|
||||
DeviceController: controllers.NewDeviceController(baseController, devService, telemService),
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
// Package virtualdata will have cool features like:
|
||||
// - fuel calculator
|
||||
// - wheel lockup and whatever lights features
|
||||
package virtualdata
|
||||
Reference in New Issue
Block a user