Author SHA1 Message Date
esilva d13ffe7821 Merge pull request 'chore: readme updated' (#21) from docs into master
Reviewed-on: #21
2026-11-08 23:19:22 +00:00
esilva 5da82a6ec3 chore: readme updated
chore: small changes
2026-11-08 23:18:01 +00:00
esilva 2fd6f6abb6 Merge pull request 'Auto detect devices' (#19) from auto-detect-devices into master
Reviewed-on: #19
2026-09-25 18:37:22 +01:00
esilva d102a45bee update the versions of the dependencies 2026-09-25 18:36:21 +01:00
esilva db30d9146d correct the go.mod 2026-09-25 15:24:18 +01:00
esilva 481b746aef Merge pull request 'Start streaming automatically' (#18) from start-streaming-automatically into auto-detect-devices
Reviewed-on: #18
2026-09-25 14:53:02 +01:00
esilva 48b10afbba devices and providers can now drop mid stream and then reconnect without impact 2026-09-25 14:48:29 +01:00
esilva 584d13e1fd removed unecessary logs from the providers and also implemented the connection dropped into beamng
This needs to be reworked tho. There's lots of code thats used both in
BeamNG and iRacing. I believe other providers will have the same issue
2026-09-25 14:47:41 +01:00
esilva d677c66a22 automated stream start
May return the user ability of stopping and starting but its really
what we want
2026-09-25 11:06:33 +01:00
esilva d14649d80c Merge pull request 'Mid stream peripheral connection' (#16) from mid-stream-peripheral-connection into auto-detect-devices
Reviewed-on: #16
2026-09-23 17:42:18 +01:00
esilva 2952528a60 partial subscriptions
not really partial. they just happen per peripheral now
2026-09-23 17:41:06 +01:00
esilva a519cf473e peripheral can connect mid stream and start go into streaming immidiately 2026-09-23 13:40:31 +01:00
esilva 76d758e264 Merge pull request 'Device reconnection handling' (#15) from device-reconnection-handling into auto-detect-devices
Reviewed-on: #15
2026-09-23 10:27:52 +01:00
esilva df1e3c26fa reconnects are slightly improved
I don't really like the reset thing with the delay. I need to implement
something better later on
2026-09-22 17:07:53 +01:00
esilva 636f20df77 delete this dead code 2026-09-22 16:27:44 +01:00
esilva 82972c9665 Added healthchecks, and maybe got a bit lost 2026-09-22 16:21:50 +01:00
esilva 009609da93 fix after implementing new changes to PSS. streaming was broken 2026-09-21 16:50:55 +01:00
esilva 91f33c79ed refactored the peripheral configuration loop 2026-09-21 16:07:00 +01:00
esilva d10c6997f4 clean up a bit the logic of how we get to know whether the telemetry started on devices lookup 2026-09-21 15:55:31 +01:00
esilva b364931c80 automatic setup for devices
Its not close to being done and still need to work out the flows due to
who arrives first: telemetry or the peripheral?
2026-09-21 15:27:42 +01:00
esilva 6ff4cc3014 added a central constants package so we don't have to pull a provider if all we need is its name 2026-09-21 15:26:57 +01:00
esilva 263d3c29a3 services decoupling 2026-09-21 11:45:10 +01:00
esilva 5d5b7bfdc3 working on the peripheral state handling 2026-09-20 21:44:15 +01:00
esilva dcba0774c2 Merge pull request 'Start stop behaviour' (#12) from start-stop-behaviour into auto-detect-devices
Reviewed-on: #12
2026-09-20 15:22:18 +01:00
esilva a5c465a203 has way too many things
In short: added the ability to detect when a device has disconnected.
From this we have to achieve a way of:
- reconnecting the device
- re-subscribing to the fields it needs (it should already be subscribed
since the ESDI didn't stop tho - but for the sake of it, or in case a
device joins later)
- start sending data to it (which should be automatic given how we are
handling the devices)
2026-09-20 15:06:48 +01:00
esilva 174b27004f added error returns to the SendData method on the peripheral interface 2026-09-18 16:37:30 +01:00
esilva a2e14ba6a9 applied the same start-stop scheme to the BeamNG provider 2026-09-18 15:42:34 +01:00
esilva a6683df10b fixed the start and stop behaviour. it was crashing 2026-09-18 15:38:17 +01:00
esilva 2d4875fbd0 removed log that was just polluting everything 2026-09-18 11:07:29 +01:00
esilva 0a8f34423c Merge pull request 'decoupled the winIDs from the telemetry data' (#11) from decouple-cdash-from-field-subscription into auto-detect-devices
Reviewed-on: #11
2026-09-18 00:07:39 +01:00
38 changed files with 1395 additions and 607 deletions
+1
View File
@@ -0,0 +1 @@
# Streaming Flow
+31 -25
View File
@@ -8,47 +8,54 @@ available peripheral: [CDashDisplay](https://github.com/ESilva15/CDashDisplay).
If anyone finds this project useful for anything at all it would be pretty cool.
My main goal is to learn and have some fun.
Currently it can read from a `.ibt` file or live telemetry from iRacing.
It can only be ran from the terminal:
`go run . offline -p <port> -i <ibt-file>`
## Usage
To launch the software, compile (TBD) or just run it with: `go run . tui`
You should see something like this:
![example output in the terminal](./images/terminal_output.png)
The current behaviour is very opaque.
or to view the live data:
`go run . live -p <port>`
What is happening in the background is the software looks up for the configured
devices and for available telemetry providers.
Once it finds a device, in this case the CDashDisplay, it will try to configure
it against the available telemetry provider.
After configuring it it will automatically start streaming data from the
telemetry provider into the CDashDisplay.
Using the `arrows` you can navigate to the `stream` item on the list and then
go to the update button and press `s` to see the output on the terminal.
I upgraded the backend significantly and there's plenty of work to be done on
the frontend. I know its quite bad right now.
## Compatibility:
Games implemented so far:
- [iRacing](https://www.iracing.com/) using the [goirsdk](https://github.com/ESilva15/goirsdk)
- [BeamNG.drive](https://www.beamng.com/game/) using the [gobngsdk](https://github.com/ESilva15/gobngsdk)
Peripherals:
- [CDashDisplay](https://github.com/ESilva15/CDashDisplay)
<!-- 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
- [X] Implement the interface for a data source
- [ ] Configuration of the peripherals via ESDI
- [ ] Detection of the display
- [ ] LapTime Calculator
- [ ] A very long list useful stuff like flags, position, more info about
other drivers, track conditions and so on so forth
- [ ] Telemetry analysis tool
- [ ] Better user interface
## 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`.
I'm using a mockserver developed by myself that pretty much mimicks the telemetry
output from the actual simulators. It uses the SDKs I developed to do so with the
added bonus of being able to run the project on Linux and mainly develop it.
Just go to [TelemetryMockserver on GitHub](https://github.com/ESilva15/TelemetryMockserver) and follow
the instructions there.
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
@@ -74,4 +81,3 @@ pprof:
## Shameless begging
Hey, doesn't hurt to try, its free either way:
[Buy me a coffee!](buymeacoffee.com/ESilva_15)
+87 -93
View File
@@ -1,103 +1,97 @@
package cmd
import (
"esdi/peripheral"
"fmt"
"strconv"
repl "github.com/ESilva15/ESgoRepl"
"github.com/spf13/cobra"
)
func replCmdAction(cmd *cobra.Command, args []string) {
r := repl.NewREPL(repl.REPLCfg{
PS1: "\rESDI > ",
})
perClerk := peripheral.NewPeripheralDeviceClerk()
discoverDevicesREPLCmd := repl.Command{
Name: "discover",
Usage: "discovers connected devices",
Action: func(r *repl.REPL, args []string) error {
err := perClerk.FindDevices()
if err != nil {
return err
}
return nil
},
}
listDevicesREPLCmd := repl.Command{
Name: "list",
Usage: "lists connected devices",
Action: func(r *repl.REPL, args []string) error {
_ = perClerk.ListDevices()
return nil
},
}
listDeviceAPIREPLCmd := repl.Command{
Name: "v-api",
Usage: "shows API of a device - pass its ID",
Action: func(r *repl.REPL, args []string) error {
// We should add this to the REPL instead
if len(args) < 1 {
return fmt.Errorf("requires at least on argument")
}
// First and only argument should be the ID of the device we want to use
targetID, err := strconv.ParseInt(args[0], 10, 0)
if err != nil {
return err
}
err = perClerk.ListDeviceAPI(uint8(targetID))
if err != nil {
fmt.Println("failed to view device API: ", err.Error())
}
return nil
},
}
runDeviceAPIREPLCmd := repl.Command{
Name: "v-run",
Usage: "runs a funcion of a device - pass its ID and function name",
Action: func(r *repl.REPL, args []string) error {
// We should add this to the REPL instead
if len(args) < 3 {
return fmt.Errorf("requires at least on argument")
}
// First and only argument should be the ID of the device we want to use
targetID, err := strconv.ParseInt(args[0], 10, 0)
if err != nil {
return err
}
fnName := args[1]
fnArgs := args[2:]
err = perClerk.RunDeviceFunction(uint8(targetID), fnName, fnArgs)
if err != nil {
return err
}
return nil
},
}
r.RegisterCMD(discoverDevicesREPLCmd)
r.RegisterCMD(listDevicesREPLCmd)
r.RegisterCMD(listDeviceAPIREPLCmd)
r.RegisterCMD(runDeviceAPIREPLCmd)
r.Start()
r.Close()
// r := repl.NewREPL(repl.REPLCfg{
// PS1: "\rESDI > ",
// })
//
// perClerk := peripheral.NewPeripheralDeviceClerk()
//
// discoverDevicesREPLCmd := repl.Command{
// Name: "discover",
// Usage: "discovers connected devices",
// Action: func(r *repl.REPL, args []string) error {
// err := perClerk.FindDevices()
// if err != nil {
// return err
// }
//
// return nil
// },
// }
//
// listDevicesREPLCmd := repl.Command{
// Name: "list",
// Usage: "lists connected devices",
// Action: func(r *repl.REPL, args []string) error {
// _ = perClerk.ListDevices()
//
// return nil
// },
// }
//
// listDeviceAPIREPLCmd := repl.Command{
// Name: "v-api",
// Usage: "shows API of a device - pass its ID",
// Action: func(r *repl.REPL, args []string) error {
// // We should add this to the REPL instead
// if len(args) < 1 {
// return fmt.Errorf("requires at least on argument")
// }
//
// // First and only argument should be the ID of the device we want to use
// targetID, err := strconv.ParseInt(args[0], 10, 0)
// if err != nil {
// return err
// }
//
// err = perClerk.ListDeviceAPI(uint8(targetID))
// if err != nil {
// fmt.Println("failed to view device API: ", err.Error())
// }
//
// return nil
// },
// }
//
// runDeviceAPIREPLCmd := repl.Command{
// Name: "v-run",
// Usage: "runs a funcion of a device - pass its ID and function name",
// Action: func(r *repl.REPL, args []string) error {
// // We should add this to the REPL instead
// if len(args) < 3 {
// return fmt.Errorf("requires at least on argument")
// }
//
// // First and only argument should be the ID of the device we want to use
// targetID, err := strconv.ParseInt(args[0], 10, 0)
// if err != nil {
// return err
// }
//
// fnName := args[1]
// fnArgs := args[2:]
//
// err = perClerk.RunDeviceFunction(uint8(targetID), fnName, fnArgs)
// if err != nil {
// return err
// }
//
// return nil
// },
// }
//
// r.RegisterCMD(discoverDevicesREPLCmd)
// r.RegisterCMD(listDevicesREPLCmd)
// r.RegisterCMD(listDeviceAPIREPLCmd)
// r.RegisterCMD(runDeviceAPIREPLCmd)
//
// r.Start()
// r.Close()
}
// removeLabelCmd represents the removeLabel command
+13
View File
@@ -0,0 +1,13 @@
package constants
// Provider Names
const (
IRacingProviderName = "iRacing"
BeamNGProviderName = "BeamNG.drive"
)
// Virtual Field Names
const (
FuelCalculatorName = "FuelCalculator"
RPMLightsName = "RPMLights"
)
+1 -1
View File
@@ -73,7 +73,7 @@ func findDisplayPort() (*communication.WalkieTalkie, error) {
select {
case err = <-probeResult:
// Probe completed normally (could be success or error)
case <-time.After(2 * time.Second):
case <-time.After(1000 * time.Millisecond):
// Hard timeout reached
err = fmt.Errorf("probe completely hung/timed out: %s", port)
}
+44 -10
View File
@@ -12,6 +12,7 @@ import (
"time"
helper "esdi/helpers"
"esdi/peripheral"
"esdi/peripheral/communication"
"esdi/peripheral/communication/packets"
"esdi/peripheral/types"
@@ -32,6 +33,8 @@ const (
updateWindowCMDID types.Command = 6 // Change this to a move cmd instead
sendDataCMDID types.Command = 7
newLayoutCMDID types.Command = 8
healthCheckCMDID types.Command = 9
resetCMDID types.Command = 10
)
const (
@@ -107,10 +110,12 @@ func NewCDashState() *CDashState {
}
type CDashDisplay struct {
WT *communication.WalkieTalkie
State *CDashState
fieldToWindows map[telemetry.FieldID][]int16
bufPool sync.Pool
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
@@ -118,7 +123,7 @@ func NewCDashDisplay() (*CDashDisplay, error) {
// Look for the port
p, err := findDisplayPort()
if err != nil {
slog.Info("failed to find cdashdisplay port: %s", err.Error())
slog.Info("failed to find cdashdisplay port", "reason", err.Error())
return nil, err
}
@@ -132,10 +137,17 @@ func NewCDashDisplay() (*CDashDisplay, error) {
return &b
},
},
failedSends: 0,
FailedSendsConsecutiveLimit: 5,
}, nil
}
func (d *CDashDisplay) SendCommand() {
func (cds *CDashDisplay) Close() error {
// if cds.WT != nil {
// cds.Close()
// }
return nil
}
func (d *CDashDisplay) RegisterFieldMapping(fieldID telemetry.FieldID, winID int16) {
@@ -393,12 +405,30 @@ func (d *CDashDisplay) UnloadLayout() error {
return nil
}
func (d *CDashDisplay) SendData(data *telemetry.TelemetryData) {
func (cds *CDashDisplay) resetState() {
cds.fieldToWindows = make(map[telemetry.FieldID][]int16)
cds.State.Layout = NewLayoutTree()
}
func (cds *CDashDisplay) reset() error {
err := cds.WT.SendCommand(resetCMDID, []byte{0x01, 0x02, 0x03, 0x04}, nil)
if err != nil {
return err
}
time.Sleep(3000 * time.Millisecond)
cds.resetState()
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 := ""
@@ -408,7 +438,6 @@ func (d *CDashDisplay) SendData(data *telemetry.TelemetryData) {
curStr += fmt.Sprintf("%02x ", byte)
if byteCount == 8 {
// slog.Debug(curStr)
curStr = ""
byteCount = 0
}
@@ -417,6 +446,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
}
+9
View File
@@ -0,0 +1,9 @@
package cdashdisplay
func (cds *CDashDisplay) OnLoad() error {
return nil
}
func (cds *CDashDisplay) OnTelemetryProviderFound() error {
return nil
}
+12
View File
@@ -1,6 +1,7 @@
package cdashdisplay
import (
"esdi/peripheral/communication/packets"
"esdi/peripheral/devices"
"esdi/telemetry"
)
@@ -26,3 +27,14 @@ func (cds *CDashDisplay) RequiredFields() []telemetry.FieldID {
return fields
}
func (cds *CDashDisplay) HealthCheck() bool {
// Send the command
var health packets.HealthCheck
err := cds.WT.SendCommand(healthCheckCMDID, []byte{0x01, 0x02, 0x03, 0x04}, &health)
if err != nil {
return false
}
return true
}
+44
View File
@@ -0,0 +1,44 @@
package cdashdisplay
import (
"fmt"
"esdi/constants"
)
func (cds *CDashDisplay) setupForIracing() error {
err := cds.LoadLayout("layout.yaml")
if err != nil {
return err
}
return nil
}
func (cds *CDashDisplay) setupForBeamNG() error {
err := cds.LoadLayout("beamng.yaml")
if err != nil {
return err
}
return nil
}
func (cds *CDashDisplay) Setup(provider string) error {
// Doesn't matter which one we are picking, we need to reset the CDashDisplay
// first - we will improve this setup behaviour later on with an Update to
// change it without dropping connection or some shit
err := cds.reset()
if err != nil {
return err
}
switch provider {
case constants.IRacingProviderName:
return cds.setupForIracing()
case constants.BeamNGProviderName:
return cds.setupForBeamNG()
default:
return fmt.Errorf("unknown provider: %s", provider)
}
}
+28 -5
View File
@@ -2,28 +2,33 @@
package devices
import (
"errors"
"esdi/devices/cdashdisplay"
"esdi/devices/uidevice"
"esdi/peripheral"
)
var ErrInvalidDevice = errors.New("invalid device")
type Device struct {
Name string
Discover func() (peripheral.Peripheral, error)
// DefaultSetup func(peripheral.Peripheral) error
}
var List map[string]Device = map[string]Device{
var List map[string]*Device = map[string]*Device{
uidevice.NAME: {
Name: uidevice.NAME,
Discover: DiscoverUIDevice,
Discover: UIDeviceDiscover,
},
cdashdisplay.NAME: {
Name: cdashdisplay.NAME,
Discover: DiscoverCDashDisplay,
Discover: CDashDisplayDiscover,
},
}
func DiscoverUIDevice() (peripheral.Peripheral, error) {
func UIDeviceDiscover() (peripheral.Peripheral, error) {
uidev, err := uidevice.NewUIDevice()
if err != nil {
return nil, err
@@ -32,7 +37,11 @@ func DiscoverUIDevice() (peripheral.Peripheral, error) {
return uidev, nil
}
func DiscoverCDashDisplay() (peripheral.Peripheral, error) {
// func UIDeviceSetup(peripheral peripheral.Peripheral) error {
// return nil
// }
func CDashDisplayDiscover() (peripheral.Peripheral, error) {
// Create a cdashdisplay
display, err := cdashdisplay.NewCDashDisplay()
if err != nil {
@@ -41,3 +50,17 @@ func DiscoverCDashDisplay() (peripheral.Peripheral, error) {
return display, nil
}
// func CDashDisplaySetup(peripheral peripheral.Peripheral) error {
// cdash, ok := peripheral.(*cdashdisplay.CDashDisplay)
// if !ok {
// return ErrInvalidDevice
// }
//
// err := cdash.LoadLayout("layout.yaml")
// if err != nil {
// return err
// }
//
// return nil
// }
+20 -2
View File
@@ -17,9 +17,21 @@ func NewUIDevice() (peripheral.Peripheral, error) {
}, nil
}
func (uid *UIDevice) SendData(data *telemetry.TelemetryData) {
func (uid *UIDevice) Close() error {
if uid.dataChan != nil {
close(uid.dataChan)
}
return nil
}
func (uid *UIDevice) Setup(provider string) error {
return nil
}
func (uid *UIDevice) SendData(data *telemetry.TelemetryData) error {
if data == nil {
return
return peripheral.ErrInvalidData
}
select {
@@ -27,6 +39,8 @@ func (uid *UIDevice) SendData(data *telemetry.TelemetryData) {
default:
// Drop frame if buffer is full
}
return nil
}
func (uid *UIDevice) Name() string {
@@ -44,3 +58,7 @@ func (uid *UIDevice) RequiredFields() []telemetry.FieldID {
telemetry.RPM,
}
}
func (uid *UIDevice) HealthCheck() bool {
return true
}
+9
View File
@@ -0,0 +1,9 @@
package uidevice
func (uid *UIDevice) OnLoad() error {
return nil
}
func (uid *UIDevice) OnTelemetryProviderFound() error {
return nil
}
+3 -4
View File
@@ -1,11 +1,10 @@
module esdi
go 1.27.0
go 1.26.0
require (
github.com/ESilva15/ESgoRepl v0.1.0
github.com/ESilva15/gobngsdk v1.1.3
github.com/ESilva15/goirsdk v0.3.0
github.com/ESilva15/gobngsdk v1.2.0
github.com/ESilva15/goirsdk v0.3.9
github.com/arl/statsviz v0.8.0
github.com/gdamore/tcell/v2 v2.8.1
github.com/rivo/tview v0.42.0
+4 -6
View File
@@ -1,9 +1,7 @@
github.com/ESilva15/ESgoRepl v0.1.0 h1:hOVcRBfdP8Yw1kLr2tFoM3SetV7vxFswKjzfAtq8UgM=
github.com/ESilva15/ESgoRepl v0.1.0/go.mod h1:O2JQMyEgHy0zf9UvzvLNvp2w95T2uazc3torrzRmG9Y=
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/ESilva15/gobngsdk v1.2.0 h1:jX2ByFaIHnjCdPmrj1JiqCoNRLyu4vqIXC7++EUOCK4=
github.com/ESilva15/gobngsdk v1.2.0/go.mod h1:cKLaZRgM0tGGXDvosaSjHnxeyC5Y6rg7zCLqEUJnOzw=
github.com/ESilva15/goirsdk v0.3.9 h1:p+C7JtTTlo75Tq+CMH4bL70rItSLIotkXcHx+mCgSuc=
github.com/ESilva15/goirsdk v0.3.9/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=
Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 113 KiB

@@ -17,6 +17,7 @@ const (
CmdAckID types.Command = 2
CmdCreateWindow types.Command = 3
CmdDestroyWindow types.Command = 4
CmdHealthCheck types.Command = 9
)
var crc8Table = [256]byte{
@@ -18,3 +18,22 @@ func (pkt *NewWindowID) Validate() bool {
return true
}
type HealthCheck struct {
StartMarker byte
Response byte
EndMarker byte
}
func (pkt *HealthCheck) Validate() bool {
if pkt.StartMarker != constvar.StartOfText ||
pkt.EndMarker != constvar.EndOfText {
return false
}
if pkt.Response != 0x06 {
return false
}
return true
}
+23 -48
View File
@@ -26,8 +26,7 @@ func (wt *WalkieTalkie) ReadFramedData(size int, packet any) error {
b := make([]byte, 1)
_, err := wt.Serial.Read(b)
if err != nil {
// fmt.Fprintf(os.Stderr, "dev read: %s\n", err.Error())
return err
return fmt.Errorf("error reading incoming: %+v, err:", b, err)
}
if b[0] == constvar.StartOfText {
@@ -44,9 +43,11 @@ func (wt *WalkieTalkie) ReadFramedData(size int, packet any) error {
reader := bytes.NewReader(buf)
err = binary.Read(reader, binary.LittleEndian, packet)
if err != nil {
return err
return fmt.Errorf("error parsing incoming: %+v, err:", buf, err)
}
wt.Serial.Flush()
return nil
}
@@ -108,6 +109,15 @@ func (wt *WalkieTalkie) sendPacket(cmd types.Command, data any) error {
return err
}
// slog.Debug("# START ########################################################")
// slog.Debug(fmt.Sprintf("StartMarker: %02x", constvar.StartOfText))
// slog.Debug(fmt.Sprintf("CMD: %02x", cmd))
// slog.Debug(fmt.Sprintf("Len: %d", len(payload)))
// slog.Debug(fmt.Sprintf("Payload: %v", payload))
// slog.Debug(fmt.Sprintf("CRC: %v", CRC8(payload)))
// slog.Debug(fmt.Sprintf("EndMarker: %02x", constvar.EndOfText))
// slog.Debug("-")
packet := CMDDataPacket{
StartMarker: constvar.StartOfText,
CMD: cmd,
@@ -119,13 +129,17 @@ func (wt *WalkieTalkie) sendPacket(cmd types.Command, data any) error {
// Send the payload
serializedPacket := packet.Serialize()
// fmt.Fprintf(os.Stderr, "%+v", serializedPacket)
// slog.Debug("Serialized packet", "packet", packet)
// slog.Debug("# END ##########################################################")
_, err = wt.Serial.Write(serializedPacket)
if err != nil {
return err
}
wt.Serial.Flush()
return nil
}
@@ -147,50 +161,11 @@ func (wt *WalkieTalkie) readPacket(resp packets.Packet) error {
return nil
}
// func (wt *WalkieTalkie) sendHeader(h *header) error {
// err := wt.sendPacket(h)
// if err != nil {
// return err
// }
//
// // var ack packets.AckPacket
// // err = wt.readPacket(&ack)
// // if err != nil {
// // return err
// // }
//
// return nil
// }
// func (wt *WalkieTalkie) sendBody(payload any, resp packets.Packet) error {
// err := wt.sendPacket(payload)
// if err != nil {
// return err
// }
//
// // err = wt.readPacket(resp)
// // if err != nil {
// // return err
// // }
//
// return nil
// }
func (wt *WalkieTalkie) SendCommand(cmd types.Command, payload any,
responseBody packets.Packet) error {
// Prepare the header
// header := header{
// StartByte: constvar.StartOfText,
// CMD: cmd,
// EndByte: constvar.EndOfText,
// }
// Send the header
// err := wt.sendHeader(&header)
// if err != nil {
// return err
// }
func (wt *WalkieTalkie) SendCommand(
cmd types.Command,
payload any,
responseBody packets.Packet,
) error {
// Send the body
err := wt.sendPacket(cmd, payload)
if err != nil {
+9
View File
@@ -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")
)
+6 -1
View File
@@ -17,8 +17,13 @@ const (
type Peripheral interface {
Name() string
SendData(*telemetry.TelemetryData)
Setup(string) error
HealthCheck() bool
SendData(*telemetry.TelemetryData) error
RequiredFields() []telemetry.FieldID
OnLoad() error
OnTelemetryProviderFound() error
Close() error
}
type PeripheralDeviceClerk struct {
+88 -59
View File
@@ -8,6 +8,7 @@ import (
"sync"
"time"
"esdi/constants"
"esdi/telemetry"
bngsdk "github.com/ESilva15/gobngsdk"
@@ -27,8 +28,11 @@ type BeamNG struct {
data *telemetry.TelemetryData
updaters [telemetry.MaxFields]func(*telemetry.TelemetryField)
// Field Subscription management
boundFields map[telemetry.FieldID]bool
// stream control
streamCh chan telemetry.TelemetryData
wg sync.WaitGroup
streamCancel context.CancelFunc
// timing
@@ -36,7 +40,7 @@ type BeamNG struct {
}
const (
NAME = "BeamNG.drive"
NAME = constants.BeamNGProviderName
)
func NewBeamNGProvider(logger *slog.Logger, opts *bngsdk.Options) (*BeamNG, error) {
@@ -46,12 +50,13 @@ func NewBeamNGProvider(logger *slog.Logger, opts *bngsdk.Options) (*BeamNG, erro
}
provider := &BeamNG{
logger: logger.With("TelemetryProvider", NAME),
streamCh: make(chan telemetry.TelemetryData, 1),
data: telemetry.NewTelemetryData(),
SDK: beam,
og: &bngsdk.Outgauge{},
ticker: time.NewTicker(time.Second / 60),
logger: logger.With("TelemetryProvider", NAME),
data: telemetry.NewTelemetryData(),
SDK: beam,
og: &bngsdk.Outgauge{},
// Field subscription management
boundFields: make(map[telemetry.FieldID]bool, telemetry.MaxFields),
ticker: time.NewTicker(time.Second / 60),
}
provider.updaters = [telemetry.MaxFields]func(*telemetry.TelemetryField){
@@ -110,64 +115,82 @@ func (b *BeamNG) Stream() (<-chan telemetry.TelemetryData, error) {
ctx, b.streamCancel = context.WithCancel(context.Background())
// Start the stream
b.stream(ctx)
ch := b.stream(ctx)
return b.streamCh, nil
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)))
// TODO: this function is exactly the same in BeamNG drive now, and I reckon it will be the same
// In plenty other things. I should make it TelemetryData method
func (i *BeamNG) subscribe(fields []telemetry.FieldID) []string {
newSubscriptions := make([]string, 0, telemetry.MaxFields)
b.data.ActiveBinds = make([]telemetry.BoundField, 0, len(requestFields))
i.mut.Lock()
defer i.mut.Unlock()
// 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] {
for _, id := range fields {
if i.boundFields[id] {
continue
}
binding := telemetry.BoundField{
i.data.ActiveBinds[id] = telemetry.BoundField{
ID: id,
}
b.data.ActiveBinds = append(b.data.ActiveBinds, binding)
boundCheck[id] = true
i.boundFields[id] = true
newSubscriptions = append(newSubscriptions, telemetry.FieldNames[id])
}
slog.Debug(fmt.Sprintf("Subscribed: %+v\n", b.data.ActiveBinds))
// unsubscribe from fields we many not need anymore
for key, bound := range i.boundFields {
if _, ok := i.data.ActiveBinds[key]; bound && !ok {
delete(i.data.ActiveBinds, key)
i.boundFields[key] = false
}
}
return newSubscriptions
}
func (b *BeamNG) Subscribe(requestFields []telemetry.FieldID) []string {
// NOTE: document how the Subscribe funtion works
slog.Debug(fmt.Sprintf("Len Req: %d\n", len(requestFields)))
// First we must add the virtual fields
// we will add their dependencies and the primitives to a slice
toBind := make([]telemetry.FieldID, telemetry.MaxFields)
b.mut.Lock()
for _, id := range requestFields {
switch id {
case telemetry.RPMStateColour:
rpmLights := telemetry.NewRPMLights()
b.data.VirtualBinds[rpmLights.Name()] = rpmLights
toBind = append(toBind, rpmLights.EnsureSubscribed()...)
case telemetry.FCCurrentLap:
fuelCalc := telemetry.NewFuelCalculator(b.logger.WithGroup("FUEL CALC"))
b.data.VirtualBinds[fuelCalc.Name()] = fuelCalc
toBind = append(toBind, fuelCalc.EnsureSubscribed()...)
default:
// primitive telemetry field
toBind = append(toBind, id)
}
}
b.mut.Unlock()
newSubs := b.subscribe(toBind)
slog.Debug(fmt.Sprintf("Subscribed: %+v\n", toBind))
return newSubs
}
// Internal
func (b *BeamNG) readData() {
slog.Debug("READING THIS DATA")
// BUG: getting stuck in here
func (b *BeamNG) readData() error {
ogSnapshot, err := b.SDK.Update()
slog.Debug("THE DATA WAS READ")
if err != nil {
slog.Error("Error getting data", "error", err)
return
return err
}
b.mut.Lock()
@@ -175,28 +198,31 @@ func (b *BeamNG) readData() {
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()
return nil
}
func (b *BeamNG) stream(ctx context.Context) {
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 {
@@ -205,24 +231,27 @@ func (b *BeamNG) stream(ctx context.Context) {
default:
}
// NOTE: add a method to check if there's data available, or make this happen
select {
case <-ctx.Done():
return
case <-b.ticker.C:
slog.Debug("READING DATA")
b.readData()
slog.Debug("READ DATA")
err := b.readData()
if err != nil {
if b.streamCancel != nil {
b.streamCancel()
}
}
// Publish data
select {
case b.streamCh <- *b.data:
slog.Debug("PUBLISHED DATA")
case outCh <- *b.data:
// Successfuly read and sent data
default:
// skip this data, don't allow publishers to lag behind
}
}
}
}()
return outCh
}
+75 -46
View File
@@ -10,13 +10,14 @@ import (
"sync"
"time"
"esdi/constants"
"esdi/telemetry"
"github.com/ESilva15/goirsdk"
)
const (
NAME = "iRacing"
NAME = constants.IRacingProviderName
)
// IRacing is our iRacing telemetry data provider - its a TelemetryProvider interface
@@ -28,12 +29,14 @@ type IRacing struct {
mut sync.Mutex
data *telemetry.TelemetryData
updaters [telemetry.MaxFields]func(*telemetry.TelemetryField)
// Field Subscription management
boundFields map[telemetry.FieldID]bool
// Timing information
ticker *time.Ticker // ticker will keep polling intervals constant
// Stream
streamCh chan telemetry.TelemetryData
wg sync.WaitGroup
streamCancel context.CancelFunc
}
@@ -50,13 +53,13 @@ func NewIRacingProvider(
}
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
logger: logger,
SDK: sdk,
data: telemetry.NewTelemetryData(),
// Field subscription management
boundFields: make(map[telemetry.FieldID]bool, telemetry.MaxFields),
// TODO: make this configurable from the user side
ticker: time.NewTicker(time.Second / 240),
ticker: time.NewTicker(time.Second / 60),
}
provider.updaters = [telemetry.MaxFields]func(*telemetry.TelemetryField){
@@ -129,16 +132,19 @@ func (i *IRacing) isDataAvailable() bool {
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() {
defer close(i.streamCh)
defer i.wg.Done()
defer close(outCh)
// Put this into the configuration file
consecutiveTimeouts := 0
maxTimeouts := 30
dataEvTimeout := 100
maxTimeouts := 10
dataEvTimeout := 30
for {
// Explicitly intercept cancellation
select {
@@ -149,12 +155,11 @@ func (i *IRacing) stream(ctx context.Context) {
if i.SDK.CheckForDataEvent(time.Duration(dataEvTimeout) * time.Millisecond) {
consecutiveTimeouts = 0
i.logger.Debug("sending data", "timeouts", consecutiveTimeouts)
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
}
@@ -170,6 +175,8 @@ func (i *IRacing) stream(ctx context.Context) {
}
}
}()
return outCh
}
func (i *IRacing) readData() {
@@ -206,9 +213,9 @@ func (i *IRacing) Stream() (<-chan telemetry.TelemetryData, error) {
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) StopStream() {
@@ -217,49 +224,71 @@ func (i *IRacing) StopStream() {
}
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)))
// TODO: this function is exactly the same in BeamNG drive now, and I reckon it will be the same
// In plenty other things. I should make it TelemetryData method
func (i *IRacing) subscribe(fields []telemetry.FieldID) []string {
newSubscriptions := make([]string, 0, telemetry.MaxFields)
i.data.ActiveBinds = make([]telemetry.BoundField, 0, len(requestFields))
i.mut.Lock()
defer i.mut.Unlock()
// First we must add the virtual fields
// we will add their dependencies and the primitives to a slice
pendingBinds := make([]telemetry.FieldID, 0, telemetry.MaxFields)
for _, id := range requestFields {
switch id {
case telemetry.RPMStateColour:
i.data.VirtualBinds = append(i.data.VirtualBinds, telemetry.NewRPMLights())
case telemetry.FCCurrentLap:
i.data.VirtualBinds = append(i.data.VirtualBinds,
telemetry.NewFuelCalculator(i.logger.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] {
for _, id := range fields {
if i.boundFields[id] {
continue
}
binding := telemetry.BoundField{
i.data.ActiveBinds[id] = telemetry.BoundField{
ID: id,
}
i.data.ActiveBinds = append(i.data.ActiveBinds, binding)
boundCheck[id] = true
i.boundFields[id] = true
newSubscriptions = append(newSubscriptions, telemetry.FieldNames[id])
}
// unsubscribe from fields we many not need anymore
for key, bound := range i.boundFields {
if _, ok := i.data.ActiveBinds[key]; bound && !ok {
delete(i.data.ActiveBinds, key)
i.boundFields[key] = false
}
}
return newSubscriptions
}
func (i *IRacing) Subscribe(requestFields []telemetry.FieldID) []string {
i.logger.Debug(fmt.Sprintf("Len Req: %d\n", len(requestFields)))
// First we must add the virtual fields
// we will add their dependencies and the primitives to a slice
toBind := make([]telemetry.FieldID, 0, telemetry.MaxFields)
i.mut.Lock()
for _, id := range requestFields {
switch id {
case telemetry.RPMStateColour:
rpmLights := telemetry.NewRPMLights()
i.data.VirtualBinds[rpmLights.Name()] = rpmLights
toBind = append(toBind, rpmLights.EnsureSubscribed()...)
case telemetry.FCCurrentLap:
fuelCalc := telemetry.NewFuelCalculator(i.logger.WithGroup("FUEL CALC"))
i.data.VirtualBinds[fuelCalc.Name()] = fuelCalc
toBind = append(toBind, fuelCalc.EnsureSubscribed()...)
default:
// primitive telemetry field
toBind = append(toBind, id)
}
}
i.mut.Unlock()
newSubs := i.subscribe(toBind)
i.logger.Debug(fmt.Sprintf("Subscribed: %+v\n", i.data.ActiveBinds))
return newSubs
}
func (i *IRacing) Name() string {
+68 -81
View File
@@ -2,46 +2,40 @@ 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
// DeviceService is the API for the peripherals
type DeviceService struct {
Logger *slog.Logger
// Device discovery
mu sync.RWMutex
PSS *PeripheralStateStore // Store to track peripheral state
ctxDiscovery context.Context
ctxDiscoveryCancel context.CancelFunc
Devices map[string]peripheral.Peripheral
// Strem handling
streamCancel context.CancelFunc
TelemCh <-chan telemetry.TelemetryData
// Output
Messages chan string
// Callbacks
// Telemetry service data fetchers
telemetryProvider func() (string, error)
triggerFieldSubscription func([]telemetry.FieldID) []string
}
func NewDeviceService(logger *slog.Logger) *DeviceService {
sharedChannel := make(chan string, 10)
func NewDeviceService(logger *slog.Logger, msg chan string) *DeviceService {
dev := &DeviceService{
Devices: make(map[string]peripheral.Peripheral),
PSS: NewPeripheralStateStore(
logger.With("Service", "PeripheralStateStore"), devices.List, msg,
),
Logger: logger,
Messages: sharedChannel,
Messages: msg,
}
// Start the routine that looks for devices - should always be running in the background
@@ -49,85 +43,57 @@ func NewDeviceService(logger *slog.Logger) *DeviceService {
dev.ctxDiscovery, dev.ctxDiscoveryCancel = context.WithCancel(context.Background())
go dev.FindDevices()
// Set the callbacks for PSS
dev.PSS.telemetryProvider = dev.getTelemetryProvider
dev.PSS.onPeripheralConfigured = dev.peripheralConfigured
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()
// Getters [START] -------------------------------------------------------------
// This function is currently only being used by PSS, we may have to find a better
// pattern for this
func (ds *DeviceService) getTelemetryProvider() (string, error) {
return ds.telemetryProvider()
}
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
}
func (ds *DeviceService) GetDevices() []peripheral.Peripheral {
snapshot := ds.PSS.GetStates()
peripherals := make([]peripheral.Peripheral, 0, len(snapshot))
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)
}
for _, state := range snapshot {
if state.State < DeviceIsConfigured {
continue
}
}
}
// func (ds *DeviceService) SubscribeFields() error {
// for _, dev := range ds.Devices {
// fields := dev.RequiredFields()
// }
//
// return nil
// }
func (ds *DeviceService) RegisterDevice(dev peripheral.Peripheral) error {
ds.mu.Lock()
defer ds.mu.Unlock()
if ds.DeviceExists(dev.Name()) {
return ErrPeripheralAlreadyRegistered
peripherals = append(peripherals, state.Peripheral)
}
ds.Devices[dev.Name()] = dev
return nil
return peripherals
}
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) GetPeripheral(pname string) (peripheral.Peripheral, error) {
return ds.PSS.GetPeripheral(pname)
}
func (ds *DeviceService) DeviceExists(name string) bool {
if _, ok := ds.Devices[name]; !ok {
return false
}
return true
func (ds *DeviceService) PeripheralExists(pname string) bool {
_, err := ds.PSS.GetPeripheral(pname)
return err == nil
}
func (ds *DeviceService) StartStream() {
// Getters [END] ---------------------------------------------------------------
// Actions [START] -------------------------------------------------------------
func (ds *DeviceService) StartStream(ch <-chan telemetry.TelemetryData) {
// NOTE: i'm using this pattern a whole lot. Maybe I can create a struct to handle this
ds.SetTelemetryChannel(ch)
var ctx context.Context
ctx, ds.streamCancel = context.WithCancel(context.Background())
ds.PSS.OnStartStream()
go ds.transmit(ctx)
ds.Messages <- "Device service started stream\n"
}
func (ds *DeviceService) StopStream() {
@@ -135,6 +101,8 @@ func (ds *DeviceService) StopStream() {
return
}
ds.PSS.OnStopStream()
ds.streamCancel()
ds.streamCancel = nil
}
@@ -144,6 +112,8 @@ func (ds *DeviceService) SetTelemetryChannel(ch <-chan telemetry.TelemetryData)
ds.TelemCh = ch
}
// Actions [END] ---------------------------------------------------------------
// transmit will send the data to the devices themselves
func (ds *DeviceService) transmit(ctx context.Context) {
var isSending atomic.Bool
@@ -165,13 +135,30 @@ func (ds *DeviceService) transmit(ctx context.Context) {
// 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 {
dev.SendData(&data)
for _, dev := range ds.PSS.GetStates() {
if dev.State != DeviceIsStreaming {
continue
}
err := dev.Peripheral.SendData(&data)
if err == peripheral.ErrDeviceTimedOut {
ds.onDeviceTimedOut(dev.device.Name)
}
}
ds.mu.RUnlock()
isSending.Store(false)
}
}
}
// Callbacks [START] -----------------------------------------------------------
func (ds *DeviceService) peripheralConfigured(pname string, fields []telemetry.FieldID) {
// We need to retrigger field subscription here
subscribedTo := ds.triggerFieldSubscription(fields)
ds.Messages <- fmt.Sprintf("subscribed to fields: %q\n", subscribedTo)
ds.PSS.OnStartStreamPeripheral(pname)
}
// Callbacks [END] -------------------------------------------------------------
+6
View File
@@ -0,0 +1,6 @@
package services
func (ds *DeviceService) OnStoppedMidStream() {
// Need to make every device be unconfigured
ds.StopStream()
}
+510
View File
@@ -0,0 +1,510 @@
package services
import (
"errors"
"fmt"
"log/slog"
"maps"
"sync"
"time"
"esdi/devices"
"esdi/peripheral"
"esdi/telemetry"
)
var (
ErrPeripheralAlreadyRegistered = errors.New("peripheral is already registered")
ErrNoSuchDevice = errors.New("device doesn't exist")
ErrDeviceIsNotConnected = errors.New("device isn't connected")
ErrFailedToSetupPeripheral = errors.New("peripheral setup failed")
)
type DeviceState = uint8
const (
DeviceTimedOut uint8 = iota
DeviceIsDisconnected
DeviceReconnected
DeviceIsDiscovering
DeviceIsConnected
DeviceIsUnconfigured
DeviceIsConfiguring
DeviceIsConfigured
DeviceIsStreaming
)
func DeviceStateToStr(state DeviceState) string {
switch state {
case DeviceTimedOut:
return "DeviceTimedOut"
case DeviceIsDisconnected:
return "DeviceIsDisconnected"
case DeviceReconnected:
return "DeviceReconnected"
case DeviceIsDiscovering:
return "DeviceIsDiscovering"
case DeviceIsConnected:
return "DeviceIsConnected"
case DeviceIsUnconfigured:
return "DeviceIsUnconfigured"
case DeviceIsConfiguring:
return "DeviceIsConfiguring"
case DeviceIsConfigured:
return "DeviceIsConfigured"
case DeviceIsStreaming:
return "DeviceIsStreaming"
default:
return "UnknownState"
}
}
type PeripheralState struct {
device *devices.Device
Peripheral peripheral.Peripheral
State DeviceState
}
func NewPeripheralState(
dev *devices.Device,
peripheral peripheral.Peripheral,
state DeviceState,
) *PeripheralState {
perState := PeripheralState{
device: dev,
Peripheral: peripheral,
State: state,
}
return &perState
}
type PeripheralStateStore struct {
Logger *slog.Logger
mu sync.RWMutex
store map[string]*PeripheralState
// Messaging for UI and stuff
Messages chan string
// Callbacks
telemetryProvider func() (string, error)
onPeripheralConfigured func(string, []telemetry.FieldID)
// Internal State
isStreaming bool
}
func NewPeripheralStateStore(
nLogger *slog.Logger,
devList map[string]*devices.Device,
msg chan string,
) *PeripheralStateStore {
store := PeripheralStateStore{
Logger: nLogger,
store: make(map[string]*PeripheralState),
Messages: msg,
}
for _, dev := range devList {
store.AddDevice(dev)
}
return &store
}
func (pss *PeripheralStateStore) GetStates() map[string]*PeripheralState {
pss.mu.RLock()
defer pss.mu.RUnlock()
return maps.Clone(pss.store)
}
func (pss *PeripheralStateStore) GetState(pname string) (*PeripheralState, error) {
if !pss.DeviceExists(pname) {
return nil, ErrNoSuchDevice
}
pss.mu.RLock()
defer pss.mu.RUnlock()
return pss.store[pname], nil
}
func (pss *PeripheralStateStore) GetPeripheral(pname string) (peripheral.Peripheral, error) {
state, err := pss.GetState(pname)
if err != nil {
return nil, err
}
if state.State < DeviceIsConnected {
return nil, ErrDeviceIsNotConnected
}
return state.Peripheral, nil
}
// AddDevice adds a new device for tracking
func (pss *PeripheralStateStore) AddDevice(dev *devices.Device) error {
if pss.DeviceExists(dev.Name) {
return ErrPeripheralAlreadyRegistered
}
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[dev.Name] = NewPeripheralState(dev, nil, DeviceIsDisconnected)
return nil
}
// DeviceExists returns whether the store is already tracking `pname`
func (pss *PeripheralStateStore) DeviceExists(pname string) bool {
pss.mu.RLock()
defer pss.mu.RUnlock()
if _, ok := pss.store[pname]; ok {
return true
}
return false
}
// DeleteDevice deletes `pname` from tracking
func (pss *PeripheralStateStore) DeleteDevice(pname string) error {
if !pss.DeviceExists(pname) {
return ErrNoSuchDevice
}
pss.mu.Lock()
defer pss.mu.Unlock()
delete(pss.store, pname)
return nil
}
func (pss *PeripheralStateStore) GetStreamingState() bool {
pss.mu.RLock()
defer pss.mu.RUnlock()
return pss.isStreaming
}
func (pss *PeripheralStateStore) GetPeripheralFields(pname string) []telemetry.FieldID {
per, err := pss.GetState(pname)
if err != nil {
return nil
}
return per.Peripheral.RequiredFields()
}
// "Events" [START] ------------------------------------------------------------
func (ds *DeviceService) onDeviceTimedOut(pname string) {
ds.PSS.setDeviceTimedOut(pname)
}
func (pss *PeripheralStateStore) OnStartStream() {
pss.mu.Lock()
pss.isStreaming = true
pss.mu.Unlock()
for _, state := range pss.GetStates() {
if state.State == DeviceIsConfigured {
pss.setDeviceIsStreaming(state.device.Name)
}
}
}
func (pss *PeripheralStateStore) OnStartStreamPeripheral(pname string) {
state, err := pss.GetState(pname)
if err != nil {
return
}
if state.State == DeviceIsConfigured {
pss.setDeviceIsStreaming(pname)
}
}
func (pss *PeripheralStateStore) OnStopStream() {
pss.mu.Lock()
pss.isStreaming = false
pss.mu.Unlock()
for _, state := range pss.GetStates() {
if state.State > DeviceIsConfigured {
pss.setDeviceUnconfigured(state.device.Name)
}
}
}
// "Events" [END] --------------------------------------------------------------
// Device State Handling [START] -----------------------------------------------
func (pss *PeripheralStateStore) setDeviceDisconnected(pname string) {
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[pname].State = DeviceIsDisconnected
}
func (pss *PeripheralStateStore) setDeviceIsDiscovering(pname string) {
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[pname].State = DeviceIsDiscovering
}
func (pss *PeripheralStateStore) setDeviceConnected(pname string, per peripheral.Peripheral) {
pss.Logger.Info("found device", "device", pname)
pss.mu.Lock()
pss.store[pname].Peripheral = per
pss.store[pname].State = DeviceIsConnected
pss.mu.Unlock()
pss.Messages <- fmt.Sprintf("Device successfuly connected: %s\n", pname)
}
func (pss *PeripheralStateStore) setDeviceTimedOut(pname string) {
pss.Logger.Info("device timed out", "device", pname)
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[pname].Peripheral = nil
pss.store[pname].State = DeviceTimedOut
}
func (pss *PeripheralStateStore) setDeviceReconnected(pname string, per peripheral.Peripheral) {
pss.Logger.Info("device reconnecting", "device", pname)
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[pname].Peripheral = per
pss.store[pname].State = DeviceReconnected
}
func (pss *PeripheralStateStore) setDeviceUnconfigured(pname string) {
pss.Logger.Info("device is connected but not configured", "device", pname)
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[pname].State = DeviceIsUnconfigured
}
func (pss *PeripheralStateStore) setDeviceIsConfiguring(pname string) {
pss.Logger.Info("device is configuring for new provider", "device", pname)
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[pname].State = DeviceIsConfiguring
}
func (pss *PeripheralStateStore) setDeviceConfigured(pname string) {
pss.Logger.Info("device is configured and ready for data", "device", pname)
pss.mu.Lock()
pss.store[pname].State = DeviceIsConfigured
pss.mu.Unlock()
pss.onPeripheralConfigured(pname, pss.GetPeripheralFields(pname))
}
func (pss *PeripheralStateStore) setDeviceIsStreaming(pname string) {
pss.Logger.Info("device is configured and ready for data", "device", pname)
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[pname].State = DeviceIsStreaming
}
// Device State Handling [END] -------------------------------------------------
// Device Handling [START] -----------------------------------------------------
func (pss *PeripheralStateStore) discoverPeripheral(
pname string,
onDiscovery func(string, peripheral.Peripheral),
onFailure func(string),
) {
pss.Logger.Debug("looking for device", "name", pname)
pss.setDeviceIsDiscovering(pname)
pss.Messages <- "Discovering " + pname + "\n"
go func() {
state, err := pss.GetState(pname)
if err != nil {
pss.Logger.Error("Can't reconnect device", "device", pname, "error", err)
onFailure(pname)
return
}
dev, err := state.device.Discover()
if err != nil {
onFailure(pname)
return
}
// Register the device we just found
onDiscovery(pname, dev)
}()
}
func (pss *PeripheralStateStore) configurePeripheral(
pname string,
onSuccess func(string),
onFailure func(string),
) {
go func() {
state, err := pss.GetState(pname)
if err != nil {
onFailure(pname)
return
}
provider, err := pss.telemetryProvider()
if err != nil {
onFailure(pname)
return
}
pss.Messages <- fmt.Sprintf("Configuring peripheral for provider: %s\n", provider)
err = state.Peripheral.Setup(provider)
if err != nil {
onFailure(pname)
return
}
onSuccess(pname)
}()
}
func (pss *PeripheralStateStore) handleDeviceTimedOut(pname string) error {
pss.Messages <- "device " + pname + " timed out\n"
pss.discoverPeripheral(pname, pss.setDeviceReconnected, pss.setDeviceTimedOut)
return nil
}
func (pss *PeripheralStateStore) handleDeviceReconnected(pname string) error {
// The device has reconnected, but we must set its state again
state, err := pss.GetState(pname)
if err != nil {
return err
}
// Update the peripheral state
pss.setDeviceConnected(pname, state.Peripheral)
return nil
}
// handleDeviceConnected will handle the device setup after it connects
// NOTE: should this be a state after Connected?
// Connected -> Unconfigured -> Configured I believe this would work nicely
// THIS IS A TODO ↑↑↑↑↑↑
func (pss *PeripheralStateStore) handleDeviceConnected(pname string) error {
pss.setDeviceUnconfigured(pname)
return nil
}
func (pss *PeripheralStateStore) handleDeviceIsUnconfigured(pname string) error {
// Here we need to configure our device. If no error occurs its configured!
_, err := pss.telemetryProvider()
if err != nil {
return err
}
pss.setDeviceIsConfiguring(pname)
pss.configurePeripheral(pname, pss.setDeviceConfigured, pss.setDeviceUnconfigured)
return nil
}
func (pss *PeripheralStateStore) handleDeviceIsConfigured(pname string) error {
// Here we have to check wheter we are streaming or not. If we aren't streaming
// then we ought to do a healthcheck on the peripheral
if pss.GetStreamingState() {
pss.Messages <- "returning device " + pname + " into streaming\n"
pss.setDeviceIsStreaming(pname)
}
return nil
}
func (pss *PeripheralStateStore) performHealthCheck(pname string, state *PeripheralState) bool {
healthStatus := state.Peripheral.HealthCheck()
if !healthStatus {
pss.Messages <- "peripheral " + pname + " failed healthcheck"
pss.setDeviceTimedOut(pname)
return false
}
return true
}
func (pss *PeripheralStateStore) HandleDeviceState() {
peripherals := pss.GetStates()
for pName, pState := range peripherals {
switch pState.State {
case DeviceIsDisconnected:
pss.discoverPeripheral(pName, pss.setDeviceConnected, pss.setDeviceDisconnected)
case DeviceIsDiscovering:
// We need to set a device into discovery mode so we won't retrigger discoveries
// and pool them up
case DeviceIsConnected:
// Need to check if its streaming, if its not streaming than we have to do a healthcheck
pss.Logger.Debug("Device is connected. Normal", "device", pName)
pss.handleDeviceConnected(pName)
case DeviceIsUnconfigured:
pss.Logger.Debug("Device is still being configured.", "device", pName)
pss.handleDeviceIsUnconfigured(pName)
case DeviceIsConfiguring:
// Do nothing configuration is happening in the background
case DeviceIsConfigured:
// Nothing to do here
pss.handleDeviceIsConfigured(pName)
case DeviceIsStreaming:
//
case DeviceReconnected:
// If the device has reconnected we need to reset the device and then set it as connected
pss.Logger.Debug("Device has reconnected. Clearing up state", "device", pName)
err := pss.handleDeviceReconnected(pName)
if err != nil {
pss.Logger.Error("device reconnection handler failed", "error", err)
continue
}
case DeviceTimedOut:
// If the device has timed out we need to re-discover it or something
pss.Logger.Debug("Device is timed out. Attempting to recconect", "device", pName)
err := pss.handleDeviceTimedOut(pName)
if err != nil {
pss.Logger.Error("device timing out handler failed", "error", err)
continue
}
}
updatedState, err := pss.GetState(pName)
if err != nil {
// TODO: log something useful here
continue
}
if updatedState.State == DeviceIsConnected ||
updatedState.State == DeviceIsUnconfigured ||
updatedState.State == DeviceIsConfigured {
pss.performHealthCheck(pName, updatedState)
}
}
}
// Device Handling [END] -------------------------------------------------------
// FindDevices is a routine that goes over the devices in the PeripheralStateStore
// and handles their state accordingly
func (ds *DeviceService) FindDevices() {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ds.ctxDiscovery.Done():
return
case <-ticker.C:
ds.PSS.HandleDeviceState()
}
}
}
+38
View File
@@ -1,2 +1,40 @@
// Package services interacts with the other libraries required for this UI
package services
import (
"errors"
"log/slog"
)
type Orchestrator struct {
DeviceService *DeviceService
TelemetryService *TelemetryService
Messages chan string
}
func NewOrchestrator(logger *slog.Logger) (*Orchestrator, error) {
msg := make(chan string, 10)
devService := NewDeviceService(logger.With("service", "DeviceService"), msg)
telemService := NewTelemetryService(logger.With("service", "TelemetryService"), msg)
if telemService == nil {
return nil, errors.New("failed to create telemetry service")
}
go telemService.FindProvider(telemService.CtxMonitor)
// Setup device service callbacks
devService.telemetryProvider = telemService.GetTelemetryProviderName
devService.triggerFieldSubscription = telemService.SubscribeToFields
// Setup telemetry service callbacks
telemService.startedStreaming = devService.StartStream
telemService.providerStoppedMidStream = devService.OnStoppedMidStream
return &Orchestrator{
DeviceService: devService,
TelemetryService: telemService,
Messages: msg,
}, nil
}
+134 -129
View File
@@ -2,6 +2,7 @@ package services
import (
"context"
"errors"
"log/slog"
"sync"
"time"
@@ -11,11 +12,14 @@ import (
telem "esdi/telemetry"
)
var ErrNoActiveProviderAvailable = errors.New("no active provider available")
// 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
logger *slog.Logger
// Streaming
isStreaming bool
// Concurrency protection
mut sync.RWMutex
activeProvider telem.TelemetryProvider
@@ -30,16 +34,23 @@ type TelemetryService struct {
cancelMonitor context.CancelFunc
CtxHealthcheck context.Context
healthCheckCancel context.CancelFunc
// Callbacks
startedStreaming func(ch <-chan telemetry.TelemetryData)
providerStoppedMidStream func()
// Devices data request
// peripheralProvider func() []peripheral.Peripheral
// getRequiredFields func() []telemetry.FieldID
}
func NewTelemetryService(logger *slog.Logger, devServo *DeviceService) *TelemetryService {
sharedChannel := make(chan string, 10)
func NewTelemetryService(
logger *slog.Logger,
msg chan string,
) *TelemetryService {
newService := &TelemetryService{
logger: logger,
isConnected: false,
devService: devServo,
listeners: make(map[string]chan telem.TelemetryData),
Messages: sharedChannel,
Messages: msg,
}
newService.CtxMonitor, newService.cancelMonitor = context.WithCancel(context.Background())
@@ -57,6 +68,7 @@ func (t *TelemetryService) ProviderMonitor(ctx context.Context) {
case <-ticker.C:
slog.Info("checking if provider is still running")
if !t.activeProvider.IsAlive(500 * time.Millisecond) {
t.Messages <- "Healthcheck on provider failing. Dropping provider.\n"
slog.Warn("provider healthcheck failed")
t.dropActiveProvider()
t.onProviderHealthCheckFailed()
@@ -66,32 +78,87 @@ func (t *TelemetryService) ProviderMonitor(ctx context.Context) {
}
}
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
func (t *TelemetryService) GetTelemetryProviderName() (string, error) {
if t.activeProvider == nil {
return "", ErrNoActiveProviderAvailable
}
// 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)
return t.activeProvider.Name(), nil
}
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)
// 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(fields []telemetry.FieldID) []string {
t.logger.Debug("requested fields", "fields", fields)
subscribed := t.activeProvider.Subscribe(fields)
return subscribed
}
// 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()
}
// NOTE: can we move the stop stream into the provider Close() method?
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
}
// TODO: add some way of retriggering this. Currently it should:
@@ -123,19 +190,46 @@ func (t *TelemetryService) FindProvider(ctx context.Context) {
}
}
func (t *TelemetryService) SwitchProvider(newProvider telem.TelemetryProvider) error {
// Provider Control [END] ------------------------------------------------------
// Streaming Control [START] ---------------------------------------------------
func (t *TelemetryService) StopStream() {
t.mut.Lock()
defer t.mut.Unlock()
// Clean up the current to be old provider
if t.activeProvider != nil {
t.dropActiveProvider()
if t.cancelForward != nil {
t.cancelForward()
t.cancelForward = nil
}
// Assign the new provider
t.activeProvider = newProvider
t.activeProvider.StopStream()
t.isStreaming = false
}
return nil
func (t *TelemetryService) StartStream() <-chan telemetry.TelemetryData {
// Start the new stream
if t.activeProvider == nil {
slog.Debug("there's no active provider. not starting the stream")
return nil
}
// Stop the provider healthcheck
t.healthCheckCancel()
simInCh, _ := t.activeProvider.Stream()
// 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
t.Messages <- "Provider has started streaming data\n"
return simInCh
}
func (t *TelemetryService) multiplexData(ctx context.Context, dataCh <-chan telem.TelemetryData) {
@@ -165,101 +259,12 @@ func (t *TelemetryService) multiplexData(ctx context.Context, dataCh <-chan tele
}
}
func (t *TelemetryService) dropActiveProvider() {
if t.cancelForward != nil {
t.cancelForward()
}
t.activeProvider.StopStream()
t.activeProvider.Close()
t.activeProvider = nil
func (t *TelemetryService) IsStreaming() bool {
return t.isStreaming
}
func (t *TelemetryService) SubscribeListener(id string, bufferSize int) <-chan telem.TelemetryData {
t.mut.Lock()
defer t.mut.Unlock()
// Streaming Control [END] -----------------------------------------------------
// NOTE: is this truly necessary?
// return the channel if it already exists
if ch, exists := t.listeners[id]; exists {
return ch
}
// Callbacks [START] -----------------------------------------------------------
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() {
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)
}
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)
}
func (t *TelemetryService) StopStream() {
t.mut.Lock()
defer t.mut.Unlock()
if t.cancelForward != nil {
t.cancelForward()
t.cancelForward = nil
}
t.activeProvider.StopStream()
}
func (t *TelemetryService) HasActiveProvider() bool {
if t.activeProvider == nil {
return false
}
return true
}
// Callbacks [END] -------------------------------------------------------------
+49
View File
@@ -0,0 +1,49 @@
package services
import (
"context"
"fmt"
telem "esdi/telemetry"
)
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())
t.Messages <- fmt.Sprintf("Found provider \"%s\"\n", prov.Name())
err := t.SwitchProvider(prov)
if err != nil {
t.Messages <- fmt.Sprintf("Failed to switch to provider: %+v\n", err.Error())
t.logger.Error("failed to switch to provider onFindProvider", "err", err)
return
}
// Start the healthcheck on our provider so we can drop it if it stops
t.CtxHealthcheck, t.healthCheckCancel = context.WithCancel(context.Background())
go t.ProviderMonitor(t.CtxHealthcheck)
ch := t.StartStream()
t.startedStreaming(ch)
t.Messages <- "provider switch completed"
}
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.Messages <- "Telemetry provider stopped mid stream\n"
t.logger.Info("cleaning dropped provider and restarting lookup service")
t.dropActiveProvider()
go t.FindProvider(t.CtxMonitor)
// Tell the devices service that we lost the thing
t.providerStoppedMidStream()
}
+6 -11
View File
@@ -23,13 +23,6 @@ type FieldMapper struct {
Transform func(any) uint64
}
// VirtualField will derive data from telemetry primitives
// So fuel per lap predictions, compound gauge lights and so on
type VirtualField interface {
Process(td *TelemetryData)
EnsureSubscribed() []FieldID
}
// 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
@@ -228,16 +221,18 @@ func GetFieldID(name string) (FieldID, bool) {
}
// TelemetryData is
// I need to find a way of having the values be per window or some other
type TelemetryData struct {
Values [MaxFields]TelemetryField
ActiveBinds []BoundField
VirtualBinds []VirtualField
ActiveBinds map[FieldID]BoundField
VirtualBinds map[string]VirtualField
InitialTime time.Time
PenultimateDataPoll time.Time
LastDataPoll time.Time
}
func NewTelemetryData() *TelemetryData {
return &TelemetryData{}
return &TelemetryData{
ActiveBinds: make(map[FieldID]BoundField, MaxFields),
VirtualBinds: make(map[string]VirtualField),
}
}
+6
View File
@@ -5,6 +5,8 @@ import (
"log/slog"
"strconv"
"sync"
"esdi/constants"
)
// NOTE: for managing fuel consumption and predictions we need to filter out
@@ -264,3 +266,7 @@ func (fc *FuelCalculator) resetHistory() {
func (fc *FuelCalculator) EnsureSubscribed() []FieldID {
return []FieldID{FuelLevel, LapNumber}
}
func (fc *FuelCalculator) Name() string {
return constants.FuelCalculatorName
}
+1 -1
View File
@@ -6,7 +6,7 @@ import "time"
type TelemetryProvider interface {
StopStream()
Stream() (<-chan TelemetryData, error)
Subscribe([]FieldID)
Subscribe([]FieldID) []string
IsAlive(time.Duration) bool
Name() string
Close()
+6
View File
@@ -1,5 +1,7 @@
package telemetry
import "esdi/constants"
type RPMLights struct {
State string
}
@@ -28,3 +30,7 @@ func (rl *RPMLights) Process(td *TelemetryData) {
func (rl *RPMLights) EnsureSubscribed() []FieldID {
return []FieldID{RPM}
}
func (rl *RPMLights) Name() string {
return constants.RPMLightsName
}
+9
View File
@@ -0,0 +1,9 @@
package telemetry
// VirtualField will derive data from telemetry primitives
// So fuel per lap predictions, compound gauge lights and so on
type VirtualField interface {
Name() string
Process(td *TelemetryData)
EnsureSubscribed() []FieldID
}
@@ -35,6 +35,7 @@ func NewLayoutController(base *Controller, service *services.DeviceService) *Lay
DevService: service,
MoveToolState: &windowManipState{Mode: moveMode},
// SelectedLayout: "beamng.yaml",
// TODO: this can't be here - the service/peripheral needs to know about it
SelectedLayout: "layout.yaml",
}
@@ -211,7 +212,7 @@ func (lc *LayoutController) createWindow() {
}
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return
@@ -321,7 +322,7 @@ func (lc *LayoutController) newWindowAction() {
func (lc *LayoutController) updateWindowAction(win *cdashdisplay.DesktopUIWindow) {
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return
@@ -347,7 +348,7 @@ func (lc *LayoutController) displayLoadedLayouts() {
lc.Logger.Debug("We want to view our layout!")
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return
@@ -392,7 +393,7 @@ func (lc *LayoutController) getCurrentTreeNodeModel() (*tview.TreeNode, int16, e
func (lc *LayoutController) loadLayout() {
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return
@@ -404,7 +405,8 @@ func (lc *LayoutController) loadLayout() {
}
// ---
// We would get the layout path from somewhere but for nots its layout.yaml
// TODO: This can happen here, but we need to address how the layout is gotten
// THE UI SHOULD SET STATE IN THE SERVICES ONLY
err = display.LoadLayout(lc.SelectedLayout)
if err != nil {
lc.Messages <- "failed to load layout: " + err.Error()
@@ -416,7 +418,7 @@ func (lc *LayoutController) loadLayout() {
func (lc *LayoutController) unloadLayout() {
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return
@@ -437,7 +439,7 @@ func (lc *LayoutController) unloadLayout() {
func (lc *LayoutController) saveLayout() {
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return
@@ -470,7 +472,7 @@ func (lc *LayoutController) deleteWindow() {
wID := curNode.GetReference().(int16)
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return
@@ -52,7 +52,7 @@ func (lc *LayoutController) handleMovementCapture(idx int16,
}
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return nil
@@ -86,7 +86,7 @@ func (lc *LayoutController) handleResizeCapture(idx int16,
}
// Acquire the cdashdisplay
displayIF, err := lc.DevService.GetDevice(cdashdisplay.NAME)
displayIF, err := lc.DevService.GetPeripheral(cdashdisplay.NAME)
if err != nil {
lc.Messages <- "failed to get " + cdashdisplay.NAME
return nil
+11 -12
View File
@@ -16,19 +16,18 @@ type DeviceController struct {
DeviceAPIView *views.DeviceAPIView
LayoutCtrl *LayoutController
StreamCtrl *StreamingCtrl
DevService *serv.DeviceService
Orchestrator *serv.Orchestrator
}
func NewDeviceController(
base *Controller,
devService *serv.DeviceService,
telemService *serv.TelemetryService,
orchestrator *serv.Orchestrator,
) *DeviceController {
mc := &DeviceController{
Controller: base,
LayoutCtrl: NewLayoutController(base, devService),
DevService: devService,
StreamCtrl: NewStreamingCtrl(base, devService, telemService),
Controller: base,
LayoutCtrl: NewLayoutController(base, orchestrator.DeviceService),
Orchestrator: orchestrator,
StreamCtrl: NewStreamingCtrl(base, orchestrator.DeviceService, orchestrator.TelemetryService),
}
return mc
@@ -57,7 +56,7 @@ func (mc *DeviceController) setDeviceAPIViewEvents() {
SetInputCapture(func(ev *tcell.EventKey) *tcell.EventKey {
switch ev.Rune() {
case 'r':
go mc.DevService.FindDevices()
go mc.Orchestrator.DeviceService.FindDevices()
}
return ev
})
@@ -67,8 +66,8 @@ 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"
if !mc.Orchestrator.DeviceService.PeripheralExists(cdashdisplay.NAME) {
mc.Orchestrator.DeviceService.Messages <- "CDashDisplay it not loaded yet\n"
return
}
@@ -94,7 +93,7 @@ func (mc *DeviceController) AddDeviceAPIListItems() {
mc.StreamCtrl.StreamView.Flex,
)
mc.StreamCtrl.SetInternalState()
// mc.StreamCtrl.SetInternalState()
mc.App.SetFocus(mc.StreamCtrl.StreamView.Options.Form)
})
@@ -116,7 +115,7 @@ func (mc *DeviceController) injectControllerCallbacks() {
func (mc *DeviceController) injectChannels() {
go func() {
for msg := range mc.DevService.Messages {
for msg := range mc.Orchestrator.Messages {
mc.PrintToOutputWindow(msg)
}
}()
+7 -54
View File
@@ -18,7 +18,7 @@ import (
type StreamingCtrl struct {
*Controller
Service *services.DeviceService
DevService *services.DeviceService
StreamView *views.StreamToolView
Messages chan string
Internal chan string
@@ -45,27 +45,20 @@ func NewStreamingCtrl(
ctrl := &StreamingCtrl{
Controller: base,
Service: devService,
DevService: devService,
TelemServ: serTelem,
Messages: make(chan string, 10),
Internal: make(chan string, 10),
TelemetryCh: make(chan telemetry.TelemetryData, 1),
Run: false,
StreamView: streamView,
isRunning: false,
}
ctrl.registerHooks()
// ctrl.subscribeListeners()
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.Options.Form.SetInputCapture(func(ev *tcell.EventKey) *tcell.EventKey {
switch ev.Key() {
@@ -95,38 +88,16 @@ func (sc *StreamingCtrl) registerHooks() {
}
}
// TODO: this isn't the startstop method/action anymore. It should show up the stream
// visualizer - TODO: add metrics to the visualizer too, instead of just data
func (sc *StreamingCtrl) StartStop() {
if sc.isRunning {
slog.Info("stopping stream")
sc.TelemServ.StopStream()
sc.Service.StopStream()
sc.isRunning = false
return
}
// 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.Service.SetTelemetryChannel(sc.TelemServ.SubscribeListener("DeviceService", 1))
dev, err := sc.Service.GetDevice(uidevice.NAME)
dev, err := sc.DevService.GetPeripheral(uidevice.NAME)
if err == nil {
if uiDev, ok := dev.(*uidevice.UIDevice); ok {
sc.TelemetryCh = uiDev.DataChannel()
go sc.listenToUIStream()
}
}
slog.Debug("starting services")
sc.Service.StartStream()
sc.TelemServ.StartStream()
sc.isRunning = true
slog.Debug("starting stream")
}
func (sc *StreamingCtrl) parseStreamUpdateForm(form *views.StreamOptionsView) (*models.StreamOptions, error) {
@@ -161,24 +132,8 @@ func (sc *StreamingCtrl) updateStream() {
// 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() {
// Acquire the cdashdisplay
// displayIF, err := sc.Service.GetDevice(cdashdisplay.NAME)
// if err != nil {
// sc.Messages <- "failed to get " + cdashdisplay.NAME
// return
// }
// display, ok := displayIF.(*cdashdisplay.CDashDisplay)
// if !ok {
// sc.Messages <- "failed to acquire " + cdashdisplay.NAME
// return
// }
// ---
sc.TelemServ.SubscribeToFields()
// sc.Messages <- fmt.Sprintf("Subscribed Fields: %+v [%d]\n", fields, len(fields))
// Should I update this?
sc.Messages <- fmt.Sprintf("Subscribed to fields\n")
// fields := sc.TelemServ.SubscribeToAllFields()
// sc.Messages <- fmt.Sprintf("Subscribed to fields: %+v\n", fields)
}
func (sc *StreamingCtrl) listenToUIStream() {
@@ -190,8 +145,6 @@ func (sc *StreamingCtrl) listenToUIStream() {
}
isDrawing.Store(true)
// sc.Logger.Debug("got data", "data", msg)
// Capture locally
telemetryMsg := msg
+5 -9
View File
@@ -23,19 +23,15 @@ func NewControlPanel(logger *slog.Logger) *ControlPanel {
App: tview.NewApplication(),
}
// 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")
orchestrator, err := services.NewOrchestrator(logger)
if err != nil {
// TODO: no panic here
panic("failed to create services orchestrator")
}
go telemService.FindProvider(telemService.CtxMonitor)
return &ControlPanel{
Controller: baseController,
DeviceController: controllers.NewDeviceController(baseController, devService, telemService),
DeviceController: controllers.NewDeviceController(baseController, orchestrator),
}
}