Author SHA1 Message Date
esilva e07f7f42de feat: putting device into user config mode when tool is opened 2026-11-08 22:34:00 +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
22 changed files with 318 additions and 163 deletions
+13
View File
@@ -1,6 +1,19 @@
package constants
// Peripheral Names
const (
CDashDisplay = "CDashDisplay"
UIView = "UIView"
)
// Provider Names
const (
IRacingProviderName = "iRacing"
BeamNGProviderName = "BeamNG.drive"
)
// Virtual Field Names
const (
FuelCalculatorName = "FuelCalculator"
RPMLightsName = "RPMLights"
)
+7
View File
@@ -405,6 +405,11 @@ func (d *CDashDisplay) UnloadLayout() error {
return nil
}
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 {
@@ -413,6 +418,8 @@ func (cds *CDashDisplay) reset() error {
time.Sleep(3000 * time.Millisecond)
cds.resetState()
return nil
}
+2 -1
View File
@@ -1,6 +1,7 @@
package uidevice
import (
"esdi/constants"
"esdi/peripheral"
"esdi/telemetry"
)
@@ -9,7 +10,7 @@ type UIDevice struct {
dataChan chan telemetry.TelemetryData
}
const NAME = "UIView"
const NAME = constants.UIView
func NewUIDevice() (peripheral.Peripheral, error) {
return &UIDevice{
+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=
+5 -2
View File
@@ -1,13 +1,16 @@
// Package devices will define the available devices we can communicate with
package devices
import "esdi/peripheral/types"
import (
"esdi/constants"
"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
CDashDisplayDevName = "CDashDisplay"
CDashDisplayDevName = constants.CDashDisplay
ESBtnBoxDevID = 0x02
)
+70 -45
View File
@@ -28,6 +28,9 @@ type BeamNG struct {
data *telemetry.TelemetryData
updaters [telemetry.MaxFields]func(*telemetry.TelemetryField)
// Field Subscription management
boundFields map[telemetry.FieldID]bool
// stream control
wg sync.WaitGroup
streamCancel context.CancelFunc
@@ -51,7 +54,9 @@ func NewBeamNGProvider(logger *slog.Logger, opts *bngsdk.Options) (*BeamNG, erro
data: telemetry.NewTelemetryData(),
SDK: beam,
og: &bngsdk.Outgauge{},
ticker: time.NewTicker(time.Second / 60),
// Field subscription management
boundFields: make(map[telemetry.FieldID]bool, telemetry.MaxFields),
ticker: time.NewTicker(time.Second / 60),
}
provider.updaters = [telemetry.MaxFields]func(*telemetry.TelemetryField){
@@ -115,58 +120,77 @@ func (b *BeamNG) Stream() (<-chan telemetry.TelemetryData, error) {
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")
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()
@@ -174,22 +198,20 @@ 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) <-chan telemetry.TelemetryData {
@@ -213,14 +235,17 @@ func (b *BeamNG) stream(ctx context.Context) <-chan telemetry.TelemetryData {
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 outCh <- *b.data:
slog.Debug("PUBLISHED DATA")
// Successfuly read and sent data
default:
// skip this data, don't allow publishers to lag behind
}
+58 -34
View File
@@ -29,13 +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
wg sync.WaitGroup
// streamCh chan telemetry.TelemetryData
wg sync.WaitGroup
streamCancel context.CancelFunc
}
@@ -55,6 +56,8 @@ func NewIRacingProvider(
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 / 60),
}
@@ -140,8 +143,8 @@ func (i *IRacing) stream(ctx context.Context) <-chan telemetry.TelemetryData {
// Put this into the configuration file
consecutiveTimeouts := 0
maxTimeouts := 30
dataEvTimeout := 100
maxTimeouts := 10
dataEvTimeout := 30
for {
// Explicitly intercept cancellation
select {
@@ -225,46 +228,67 @@ func (i *IRacing) StopStream() {
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 {
+23 -3
View File
@@ -2,6 +2,7 @@ package services
import (
"context"
"fmt"
"log/slog"
"sync/atomic"
@@ -24,7 +25,8 @@ type DeviceService struct {
Messages chan string
// Callbacks
// Telemetry service data fetchers
telemetryProvider func() (string, error)
telemetryProvider func() (string, error)
triggerFieldSubscription func([]telemetry.FieldID) []string
}
func NewDeviceService(logger *slog.Logger, msg chan string) *DeviceService {
@@ -43,6 +45,7 @@ func NewDeviceService(logger *slog.Logger, msg chan string) *DeviceService {
// Set the callbacks for PSS
dev.PSS.telemetryProvider = dev.getTelemetryProvider
dev.PSS.onPeripheralConfigured = dev.peripheralConfigured
return dev
}
@@ -59,7 +62,7 @@ func (ds *DeviceService) GetDevices() []peripheral.Peripheral {
peripherals := make([]peripheral.Peripheral, 0, len(snapshot))
for _, state := range snapshot {
if state.State < DeviceIsConnected {
if state.State < DeviceIsConfigured {
continue
}
peripherals = append(peripherals, state.Peripheral)
@@ -80,14 +83,17 @@ func (ds *DeviceService) PeripheralExists(pname string) bool {
// Getters [END] ---------------------------------------------------------------
// Actions [START] -------------------------------------------------------------
func (ds *DeviceService) StartStream() {
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() {
@@ -95,10 +101,17 @@ func (ds *DeviceService) StopStream() {
return
}
ds.PSS.OnStopStream()
ds.streamCancel()
ds.streamCancel = nil
}
func (ds *DeviceService) SetPeripheralUserConfigMode(pname string) error {
ds.PSS.setDeviceBeingConfiguredByUser(pname)
return nil
}
// SetTelemetryChannel sets the TelemCh to the passed channel
func (ds *DeviceService) SetTelemetryChannel(ch <-chan telemetry.TelemetryData) {
ds.TelemCh = ch
@@ -145,5 +158,12 @@ func (ds *DeviceService) transmit(ctx context.Context) {
}
// 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] -------------------------------------------------------------
+5
View File
@@ -1 +1,6 @@
package services
func (ds *DeviceService) OnStoppedMidStream() {
// Need to make every device be unconfigured
ds.StopStream()
}
+46 -3
View File
@@ -10,6 +10,7 @@ import (
"esdi/devices"
"esdi/peripheral"
"esdi/telemetry"
)
var (
@@ -29,6 +30,7 @@ const (
DeviceIsConnected
DeviceIsUnconfigured
DeviceIsConfiguring
DeviceBeingConfiguredByUser
DeviceIsConfigured
DeviceIsStreaming
)
@@ -49,6 +51,8 @@ func DeviceStateToStr(state DeviceState) string {
return "DeviceIsUnconfigured"
case DeviceIsConfiguring:
return "DeviceIsConfiguring"
case DeviceBeingConfiguredByUser:
return "DeviceBeingConfiguredByUser"
case DeviceIsConfigured:
return "DeviceIsConfigured"
case DeviceIsStreaming:
@@ -85,7 +89,8 @@ type PeripheralStateStore struct {
// Messaging for UI and stuff
Messages chan string
// Callbacks
telemetryProvider func() (string, error)
telemetryProvider func() (string, error)
onPeripheralConfigured func(string, []telemetry.FieldID)
// Internal State
isStreaming bool
}
@@ -183,6 +188,15 @@ func (pss *PeripheralStateStore) GetStreamingState() bool {
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)
@@ -200,10 +214,27 @@ func (pss *PeripheralStateStore) OnStartStream() {
}
}
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] --------------------------------------------------------------
@@ -266,12 +297,22 @@ func (pss *PeripheralStateStore) setDeviceIsConfiguring(pname string) {
pss.store[pname].State = DeviceIsConfiguring
}
func (pss *PeripheralStateStore) setDeviceBeingConfiguredByUser(pname string) {
pss.Logger.Info("device is being configured by the user", "device", pname)
pss.mu.Lock()
defer pss.mu.Unlock()
pss.store[pname].State = DeviceBeingConfiguredByUser
}
func (pss *PeripheralStateStore) setDeviceConfigured(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 = DeviceIsConfigured
pss.mu.Unlock()
pss.onPeripheralConfigured(pname, pss.GetPeripheralFields(pname))
}
func (pss *PeripheralStateStore) setDeviceIsStreaming(pname string) {
@@ -330,6 +371,7 @@ func (pss *PeripheralStateStore) configurePeripheral(
onFailure(pname)
return
}
pss.Messages <- fmt.Sprintf("Configuring peripheral for provider: %s\n", provider)
err = state.Peripheral.Setup(provider)
if err != nil {
@@ -338,7 +380,6 @@ func (pss *PeripheralStateStore) configurePeripheral(
}
onSuccess(pname)
pss.setDeviceConfigured(pname)
}()
}
@@ -427,6 +468,8 @@ func (pss *PeripheralStateStore) HandleDeviceState() {
case DeviceIsConfigured:
// Nothing to do here
pss.handleDeviceIsConfigured(pName)
case DeviceBeingConfiguredByUser:
// Nothing to do here, need to wait for the user to finish
case DeviceIsStreaming:
//
case DeviceReconnected:
+3 -1
View File
@@ -26,9 +26,11 @@ func NewOrchestrator(logger *slog.Logger) (*Orchestrator, error) {
// Setup device service callbacks
devService.telemetryProvider = telemService.GetTelemetryProviderName
devService.triggerFieldSubscription = telemService.SubscribeToFields
// Setup telemetry service callbacks
telemService.peripheralProvider = devService.GetDevices
telemService.startedStreaming = devService.StartStream
telemService.providerStoppedMidStream = devService.OnStoppedMidStream
return &Orchestrator{
DeviceService: devService,
+15 -24
View File
@@ -7,7 +7,6 @@ import (
"sync"
"time"
"esdi/peripheral"
"esdi/providers"
"esdi/telemetry"
telem "esdi/telemetry"
@@ -36,8 +35,11 @@ type TelemetryService struct {
CtxHealthcheck context.Context
healthCheckCancel context.CancelFunc
// Callbacks
startedStreaming func(ch <-chan telemetry.TelemetryData)
providerStoppedMidStream func()
// Devices data request
peripheralProvider func() []peripheral.Peripheral
// peripheralProvider func() []peripheral.Peripheral
// getRequiredFields func() []telemetry.FieldID
}
func NewTelemetryService(
@@ -114,23 +116,11 @@ func (t *TelemetryService) UnsubscribeListener(id string) {
}
}
func (t *TelemetryService) SubscribeToFields() []telem.FieldID {
seen := make(map[telemetry.FieldID]struct{})
var allFields []telemetry.FieldID
func (t *TelemetryService) SubscribeToFields(fields []telemetry.FieldID) []string {
t.logger.Debug("requested fields", "fields", fields)
subscribed := t.activeProvider.Subscribe(fields)
for _, dev := range t.peripheralProvider() {
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
return subscribed
}
// Listener Control [END] ------------------------------------------------------
@@ -150,6 +140,7 @@ func (t *TelemetryService) dropActiveProvider() {
t.cancelForward()
}
// NOTE: can we move the stop stream into the provider Close() method?
t.activeProvider.StopStream()
t.activeProvider.Close()
t.activeProvider = nil
@@ -216,21 +207,17 @@ func (t *TelemetryService) StopStream() {
t.isStreaming = false
}
func (t *TelemetryService) StartStream() {
slog.Debug("Stream started")
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
return nil
}
// 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())
@@ -239,6 +226,10 @@ func (t *TelemetryService) StartStream() {
// 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) {
+10
View File
@@ -16,6 +16,7 @@ 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())
@@ -26,6 +27,11 @@ func (t *TelemetryService) onFindProvider(prov telem.TelemetryProvider) {
// 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\n"
}
func (t *TelemetryService) onProviderStopsMidStream() {
@@ -34,6 +40,10 @@ func (t *TelemetryService) onProviderStopsMidStream() {
// 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
}
@@ -5,6 +5,7 @@ import (
"os"
"strconv"
"esdi/constants"
"esdi/devices/cdashdisplay"
"esdi/services"
"esdi/tui/internal/views"
@@ -585,3 +586,21 @@ func (lc *LayoutController) changeSelectedLoadout() {
lc.LayoutToolView.ShowLayoutList()
lc.App.SetFocus(lc.LayoutToolView.LayoutActions.LayoutSelection.Tree)
}
// ##### Event Listener
// OnLayoutToolOpen we need to change focus to the layout tool and move the
// device out of streaming mode or whatever.
// - start by making sure that device is able to be configured
func (lc *LayoutController) OnLayoutToolOpen() {
// Get the device from somewhere
cdash, err := lc.DevService.GetPeripheral(constants.CDashDisplay)
if err != nil {
lc.Messages <- "failed to acquire CDashDisplay " + err.Error() + "\n"
return
}
lc.DevService.SetPeripheralUserConfigMode(cdash.Name())
// Change focus to the layout tree
lc.App.SetFocus(lc.LayoutToolView.LayoutTree.Tree)
}
+3 -2
View File
@@ -77,7 +77,8 @@ func (mc *DeviceController) AddDeviceAPIListItems() {
"layout-tool",
mc.LayoutCtrl.LayoutToolView.Flex,
)
mc.App.SetFocus(mc.LayoutCtrl.LayoutToolView.LayoutTree.Tree)
mc.LayoutCtrl.OnLayoutToolOpen()
})
mc.DeviceAPIView.DevAPIList.
AddItem("stream", "stream data to the display", func() {
@@ -93,7 +94,7 @@ func (mc *DeviceController) AddDeviceAPIListItems() {
mc.StreamCtrl.StreamView.Flex,
)
mc.StreamCtrl.SetInternalState()
// mc.StreamCtrl.SetInternalState()
mc.App.SetFocus(mc.StreamCtrl.StreamView.Options.Form)
})
+4 -26
View File
@@ -88,23 +88,9 @@ 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.TelemServ.IsStreaming() {
slog.Info("stopping stream")
sc.TelemServ.StopStream()
sc.DevService.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.DevService.SetTelemetryChannel(sc.TelemServ.SubscribeListener("DeviceService", 1))
dev, err := sc.DevService.GetPeripheral(uidevice.NAME)
if err == nil {
if uiDev, ok := dev.(*uidevice.UIDevice); ok {
@@ -112,14 +98,6 @@ func (sc *StreamingCtrl) StartStop() {
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) {
@@ -154,8 +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() {
fields := sc.TelemServ.SubscribeToFields()
sc.Messages <- fmt.Sprintf("Subscribed to fields: %+v\n", fields)
// fields := sc.TelemServ.SubscribeToAllFields()
// sc.Messages <- fmt.Sprintf("Subscribed to fields: %+v\n", fields)
}
func (sc *StreamingCtrl) listenToUIStream() {