server

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 25, 2026 License: Apache-2.0 Imports: 47 Imported by: 0

Documentation

Overview

Package server provides thin HTTP handler shells for LiDAR chart endpoints. Data preparation and types live in l9endpoints; these handlers only parse requests, obtain data sources, delegate to l9endpoints, and write responses.

Package server provides HTTP client operations for LiDAR monitoring endpoints.

Package server provides mock implementations for testing.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoSourceActive = errors.New("no data source active")

ErrNoSourceActive is returned when trying to stop a source that's not active.

View Source
var ErrSourceAlreadyActive = errors.New("data source already active")

ErrSourceAlreadyActive is returned when trying to start a source that's already active.

Functions

func DefaultBuckets

func DefaultBuckets() []string

DefaultBuckets returns the default bucket configuration.

func FormatWithCommas

func FormatWithCommas(n int64) string

FormatWithCommas formats a number with thousands separators

func SetLogWriters

func SetLogWriters(ops, diag, trace io.Writer)

SetLogWriters configures the three logging streams for the monitor package. Pass nil for any writer to disable that stream.

Types

type AutoTuneRunner

type AutoTuneRunner interface {
	Start(ctx context.Context, req interface{}) error
	GetState() interface{}
	Stop()
	Suspend() error
	Resume(ctx context.Context, sweepID string) error
}

AutoTuneRunner defines the interface for auto-tune operations.

type BBox

type BBox struct {
	Length float32 `json:"length"`
	Width  float32 `json:"width"`
	Height float32 `json:"height"`
}

BBox represents bounding box dimensions for rendering. These are per-frame cluster dimensions (from DBSCAN OBB), not running averages.

type BackgroundManagerInterface

type BackgroundManagerInterface interface {
	// GetGridCells returns exported cells for polar chart rendering
	GetGridCells() []l3grid.ExportedCell
	// GetGridHeatmap returns aggregated heatmap buckets
	GetGridHeatmap(azimuthBucketDeg float64, settledThreshold uint32) *l3grid.GridHeatmap
	// GetParams returns the current background parameters
	GetParams() l3grid.BackgroundParams
	// SetParams updates background parameters
	SetParams(p l3grid.BackgroundParams) error
	// SetNoiseRelativeFraction updates the noise relative fraction
	SetNoiseRelativeFraction(v float32) error
	// GetGrid returns the underlying grid (nil check used)
	GetGrid() *l3grid.BackgroundGrid
	// IsDiagnosticsEnabled returns whether diagnostics are enabled
	IsDiagnosticsEnabled() bool
	// SetDiagnosticsEnabled enables or disables diagnostics
	SetDiagnosticsEnabled(enabled bool)
}

BackgroundManagerInterface defines the subset of BackgroundManager methods used by the Server for chart data and configuration.

type BackgroundManagerProvider

type BackgroundManagerProvider interface {
	GetBackgroundManager(sensorID string) BackgroundManagerInterface
}

BackgroundManagerProvider abstracts background manager access for testing. Production code uses the global registry; tests can inject mocks.

type BackgroundParams

type BackgroundParams struct {
	NoiseRelative              float64
	ClosenessMultiplier        float64
	NeighbourConfirmationCount int
	SeedFromFirst              bool
}

BackgroundParams holds the parameters for the background model. Serialises as nested JSON matching tuning.defaults.json structure.

func (BackgroundParams) MarshalJSON

func (p BackgroundParams) MarshalJSON() ([]byte, error)

MarshalJSON produces nested JSON: {"l3":{"ema_baseline_v1":{...}}}.

func (*BackgroundParams) UnmarshalJSON

func (p *BackgroundParams) UnmarshalJSON(data []byte) error

UnmarshalJSON reads nested JSON: {"l3":{"ema_baseline_v1":{...}}}.

type ClassSummary

type ClassSummary = l8analytics.TrackClassSummary

ClassSummary is a type alias for l8analytics.TrackClassSummary.

type Client

type Client struct {
	HTTPClient *http.Client
	BaseURL    string
	SensorID   string
}

Client provides HTTP operations for LiDAR monitoring endpoints.

func NewClient

func NewClient(httpClient *http.Client, baseURL, sensorID string) *Client

NewClient creates a new monitoring client.

func (*Client) FetchAcceptanceMetrics

func (c *Client) FetchAcceptanceMetrics() (map[string]interface{}, error)

FetchAcceptanceMetrics fetches acceptance metrics from the server.

func (*Client) FetchBuckets

func (c *Client) FetchBuckets() []string

FetchBuckets retrieves the bucket configuration from the server. Returns default buckets on error.

func (*Client) FetchGridStatus

func (c *Client) FetchGridStatus() (map[string]interface{}, error)

FetchGridStatus fetches the grid status from the server.

func (*Client) FetchTrackingMetrics

func (c *Client) FetchTrackingMetrics() (map[string]interface{}, error)

FetchTrackingMetrics fetches velocity-trail alignment metrics from the server. Used by the sweep tool to evaluate tracking parameter quality.

func (*Client) GetLastAnalysisRunID

func (c *Client) GetLastAnalysisRunID() string

GetLastAnalysisRunID retrieves the last analysis run ID from the data source endpoint. Returns an empty string if no analysis run has been recorded.

func (*Client) GetSensorID

func (c *Client) GetSensorID() string

GetSensorID returns the sensor identifier (method form of the SensorID field).

func (*Client) ResetAcceptance

func (c *Client) ResetAcceptance() error

ResetAcceptance resets the acceptance counters.

func (*Client) ResetGrid

func (c *Client) ResetGrid() error

ResetGrid resets the background grid for the sensor.

func (*Client) SetParams

func (c *Client) SetParams(params BackgroundParams) error

SetParams sets the background model parameters.

func (*Client) SetTrackerConfig

func (c *Client) SetTrackerConfig(params TrackingParams) error

SetTrackerConfig updates tracker configuration on the server via the consolidated /api/lidar/params endpoint.

func (*Client) SetTuningParams

func (c *Client) SetTuningParams(params map[string]interface{}) error

SetTuningParams sends a partial tuning config update to /api/lidar/params. The params map can contain any TuningConfig field names with their values.

func (*Client) StartPCAPReplay

func (c *Client) StartPCAPReplay(pcapFile string, maxRetries int) error

StartPCAPReplay requests a PCAP replay for the sensor. It retries on 409 (conflict) responses for up to maxRetries times. The pcapFile path is passed through to the server as-is. Prefer relative paths (relative to the server's configured PCAP safe directory); the server may reject absolute paths that fall outside its safe directory.

func (*Client) StartPCAPReplayWithConfig

func (c *Client) StartPCAPReplayWithConfig(cfg PCAPReplayConfig) error

StartPCAPReplayWithConfig requests a PCAP replay with extended configuration. The PCAPFile in cfg should be a path relative to the server's PCAP safe directory.

func (*Client) StartPCAPReplayWithSweepConfig

func (c *Client) StartPCAPReplayWithSweepConfig(cfg sweep.PCAPReplayConfig) error

StartPCAPReplayWithSweepConfig starts a PCAP replay using the sweep-package config type. It converts to the monitor.PCAPReplayConfig and delegates.

func (*Client) StopPCAPReplay

func (c *Client) StopPCAPReplay() error

StopPCAPReplay stops any running PCAP replay for this sensor.

func (*Client) WaitForGridSettle

func (c *Client) WaitForGridSettle(timeout time.Duration)

WaitForGridSettle waits for the grid to have at least one non-zero cell.

func (*Client) WaitForPCAPComplete

func (c *Client) WaitForPCAPComplete(timeout time.Duration) error

WaitForPCAPComplete uses long-polling to wait until the PCAP replay finishes. The server blocks the request until PCAP completes, avoiding 500ms polling. Falls back to short-poll if the long-poll request fails (e.g. older server). Returns nil when the PCAP is no longer in progress, or an error on timeout.

type ClientBackend

type ClientBackend struct{ *Client }

ClientBackend wraps a *Client to satisfy sweep.SweepBackend. The wrapper is needed because the Client struct has a public SensorID field which conflicts with the interface's SensorID() method.

func NewClientBackend

func NewClientBackend(c *Client) *ClientBackend

NewClientBackend wraps an HTTP Client as a SweepBackend.

func (*ClientBackend) SensorID

func (cb *ClientBackend) SensorID() string

func (*ClientBackend) StartPCAPReplayWithConfig

func (cb *ClientBackend) StartPCAPReplayWithConfig(cfg sweep.PCAPReplayConfig) error

type ClusterResponse

type ClusterResponse struct {
	ClusterID   int64    `json:"cluster_id"`
	SensorID    string   `json:"sensor_id"`
	Timestamp   string   `json:"timestamp"`
	Centroid    Position `json:"centroid"`
	BoundingBox struct {
		Length float32 `json:"length"`
		Width  float32 `json:"width"`
		Height float32 `json:"height"`
	} `json:"bounding_box"`
	PointsCount   int     `json:"points_count"`
	HeightP95     float32 `json:"height_p95"`
	IntensityMean float32 `json:"intensity_mean"`
}

ClusterResponse represents a cluster in JSON API responses.

type ClustersListResponse

type ClustersListResponse struct {
	Clusters  []ClusterResponse `json:"clusters"`
	Count     int               `json:"count"`
	Timestamp string            `json:"timestamp"`
}

ClustersListResponse is the JSON response for listing clusters.

type Config

type Config struct {
	Address           string
	Stats             *PacketStats
	ForwardingEnabled bool
	ForwardAddr       string
	ForwardPort       int
	ParsingEnabled    bool
	UDPPort           int
	DB                *db.DB
	SensorID          string
	Parser            network.Parser
	FrameBuilder      network.FrameBuilder
	Classifier        *l6objects.TrackClassifier
	PCAPSafeDir       string // Safe directory for PCAP file access (restricts path traversal)
	VRLogSafeDir      string // Safe directory for VRLOG file access (restricts path traversal)
	PacketForwarder   *network.PacketForwarder
	UDPListenerConfig network.UDPListenerConfig
	PlotsBaseDir      string // Base directory for plot output (e.g., "plots")
	TuningConfig      *cfgpkg.TuningConfig

	// DataSourceManager allows injecting a custom data source manager.
	// If nil, a RealDataSourceManager is created automatically.
	// Inject a MockDataSourceManager for testing.
	DataSourceManager DataSourceManager

	// OnPCAPStarted is called when a PCAP replay starts successfully.
	// Used to notify the visualiser gRPC server to switch to replay mode.
	OnPCAPStarted func()

	// OnPCAPStopped is called when a PCAP replay stops and the system
	// returns to live mode. Used to notify the visualiser gRPC server.
	OnPCAPStopped func()

	// OnPCAPProgress is called periodically during PCAP replay with the
	// current and total packet counts, enabling progress/seek in the UI.
	OnPCAPProgress func(currentPacket, totalPackets uint64)

	// OnPCAPTimestamps is called after PCAP pre-counting with the first and
	// last capture timestamps, enabling timeline display in the UI.
	OnPCAPTimestamps func(startNs, endNs int64)

	// OnRecordingStart is called when VRLOG recording starts for an analysis run.
	// The callback receives the run ID and should start the recorder.
	OnRecordingStart func(runID string)

	// OnRecordingStop is called when VRLOG recording stops.
	// The callback receives the run ID and should return the path to the recorded VRLOG.
	OnRecordingStop func(runID string) string

	// Playback control callbacks
	OnPlaybackPause   func()
	OnPlaybackPlay    func()
	OnPlaybackSeek    func(timestampNs int64) error
	OnPlaybackRate    func(rate float32)
	OnVRLogLoad       func(vrlogPath string) (string, error)
	OnVRLogStop       func()
	GetPlaybackStatus func() *PlaybackStatusInfo
}

Config contains configuration options for the web server

type CreateSceneRequest

type CreateSceneRequest struct {
	SensorID         string   `json:"sensor_id"`
	PCAPFile         string   `json:"pcap_file"`
	PCAPStartSecs    *float64 `json:"pcap_start_secs,omitempty"`
	PCAPDurationSecs *float64 `json:"pcap_duration_secs,omitempty"`
	Description      string   `json:"description,omitempty"`
}

CreateSceneRequest is the request body for creating a scene.

type DataSource

type DataSource string

DataSource represents the type of data source currently active.

const (
	DataSourceLive         DataSource = "live"
	DataSourcePCAP         DataSource = "pcap"
	DataSourcePCAPAnalysis DataSource = "pcap_analysis"
)

Defined data sources for the monitor.

type DataSourceManager

type DataSourceManager interface {
	// StartLiveListener starts the live UDP listener.
	StartLiveListener(ctx context.Context) error

	// StopLiveListener stops the live UDP listener.
	StopLiveListener() error

	// StartPCAPReplay starts replaying packets from a PCAP file.
	StartPCAPReplay(ctx context.Context, file string, config ReplayConfig) error

	// StopPCAPReplay stops the current PCAP replay.
	StopPCAPReplay() error

	// CurrentSource returns the currently active data source.
	CurrentSource() DataSource

	// CurrentPCAPFile returns the currently replaying PCAP file, if any.
	CurrentPCAPFile() string

	// IsPCAPInProgress returns true if a PCAP replay is currently active.
	IsPCAPInProgress() bool
}

DataSourceManager defines an interface for managing data sources. This abstraction enables unit testing of Server without real UDP/PCAP dependencies.

type DefaultBackgroundManagerProvider

type DefaultBackgroundManagerProvider struct{}

DefaultBackgroundManagerProvider uses the global lidar registry.

func (*DefaultBackgroundManagerProvider) GetBackgroundManager

func (p *DefaultBackgroundManagerProvider) GetBackgroundManager(sensorID string) BackgroundManagerInterface

GetBackgroundManager returns the manager from the global registry.

type DirectBackend

type DirectBackend struct {
	// contains filtered or unexported fields
}

DirectBackend implements sweep.SweepBackend by calling Go methods in-process, bypassing HTTP serialisation. It eliminates all network overhead and polling loops when the sweep runner and web server live in the same binary.

func NewDirectBackend

func NewDirectBackend(sensorID string, ws *Server) *DirectBackend

NewDirectBackend creates a backend that talks directly to the server internals. The caller must pass the same webserver instance that serves the LiDAR monitor endpoints.

func (*DirectBackend) FetchAcceptanceMetrics

func (d *DirectBackend) FetchAcceptanceMetrics() (map[string]interface{}, error)

FetchAcceptanceMetrics returns acceptance counters as a generic map, matching the JSON shape the HTTP client produces.

func (*DirectBackend) FetchBuckets

func (d *DirectBackend) FetchBuckets() []string

FetchBuckets returns bucket boundary strings from the BackgroundManager.

func (*DirectBackend) FetchGridStatus

func (d *DirectBackend) FetchGridStatus() (map[string]interface{}, error)

FetchGridStatus returns background grid statistics.

func (*DirectBackend) FetchTrackingMetrics

func (d *DirectBackend) FetchTrackingMetrics() (map[string]interface{}, error)

FetchTrackingMetrics returns velocity-trail alignment metrics as a generic map matching the JSON shape produced by the HTTP handler.

func (*DirectBackend) GetLastAnalysisRunID

func (d *DirectBackend) GetLastAnalysisRunID() string

GetLastAnalysisRunID returns the last analysis run ID.

func (*DirectBackend) ResetAcceptance

func (d *DirectBackend) ResetAcceptance() error

ResetAcceptance zeroes the acceptance counters.

func (*DirectBackend) ResetGrid

func (d *DirectBackend) ResetGrid() error

ResetGrid resets the background grid, frame builder, and tracker.

func (*DirectBackend) SensorID

func (d *DirectBackend) SensorID() string

SensorID returns the sensor identifier.

func (*DirectBackend) SetTuningParams

func (d *DirectBackend) SetTuningParams(params map[string]interface{}) error

SetTuningParams applies a partial tuning config update. It mirrors the POST handler for /api/lidar/params.

func (*DirectBackend) StartPCAPReplayWithConfig

func (d *DirectBackend) StartPCAPReplayWithConfig(cfg sweep.PCAPReplayConfig) error

StartPCAPReplayWithConfig begins a PCAP replay using the Server's internal PCAP machinery, bypassing HTTP entirely.

func (*DirectBackend) StopPCAPReplay

func (d *DirectBackend) StopPCAPReplay() error

StopPCAPReplay cancels the running PCAP replay and restores live mode.

func (*DirectBackend) WaitForGridSettle

func (d *DirectBackend) WaitForGridSettle(timeout time.Duration)

WaitForGridSettle blocks until background_count > 0 or timeout.

func (*DirectBackend) WaitForPCAPComplete

func (d *DirectBackend) WaitForPCAPComplete(timeout time.Duration) error

WaitForPCAPComplete blocks on the Server's pcapDone channel until the replay finishes or timeout elapses. No HTTP overhead or polling.

type HINTRunner

type HINTRunner interface {
	Start(ctx context.Context, req interface{}) error
	GetState() interface{}
	Stop()
	ContinueFromLabels(nextDurationMins int, addRound bool) error
	// WaitForChange blocks until the HINT status differs from lastStatus
	// or the context is cancelled. Returns the new state.
	WaitForChange(ctx context.Context, lastStatus string) interface{}
	// NotifyLabelUpdate wakes the label-wait loop when a track is labelled.
	NotifyLabelUpdate()
}

HINTRunner defines the interface for HINT sweep operations.

type MockBackgroundManager

type MockBackgroundManager struct {
	Cells          []l3grid.ExportedCell
	Heatmap        *l3grid.GridHeatmap
	Params         l3grid.BackgroundParams
	Grid           *l3grid.BackgroundGrid
	Diagnostics    bool
	SetParamsErr   error
	SetNoiseErr    error
	SetParamsCalls []l3grid.BackgroundParams
	SetNoiseCalls  []float32
}

MockBackgroundManager provides a testable implementation of BackgroundManagerInterface.

func (*MockBackgroundManager) GetGrid

GetGrid returns the configured grid.

func (*MockBackgroundManager) GetGridCells

func (m *MockBackgroundManager) GetGridCells() []l3grid.ExportedCell

GetGridCells returns the configured cells.

func (*MockBackgroundManager) GetGridHeatmap

func (m *MockBackgroundManager) GetGridHeatmap(azimuthBucketDeg float64, settledThreshold uint32) *l3grid.GridHeatmap

GetGridHeatmap returns the configured heatmap.

func (*MockBackgroundManager) GetParams

GetParams returns the configured params.

func (*MockBackgroundManager) IsDiagnosticsEnabled

func (m *MockBackgroundManager) IsDiagnosticsEnabled() bool

IsDiagnosticsEnabled returns the diagnostics flag.

func (*MockBackgroundManager) SetDiagnosticsEnabled

func (m *MockBackgroundManager) SetDiagnosticsEnabled(enabled bool)

SetDiagnosticsEnabled sets the diagnostics flag.

func (*MockBackgroundManager) SetNoiseRelativeFraction

func (m *MockBackgroundManager) SetNoiseRelativeFraction(v float32) error

SetNoiseRelativeFraction records the call and returns configured error.

func (*MockBackgroundManager) SetParams

SetParams records the call and returns configured error.

type MockBackgroundManagerProvider

type MockBackgroundManagerProvider struct {
	Managers map[string]BackgroundManagerInterface
}

MockBackgroundManagerProvider provides mock managers for testing.

func NewMockBackgroundManagerProvider

func NewMockBackgroundManagerProvider(managers map[string]BackgroundManagerInterface) *MockBackgroundManagerProvider

NewMockBackgroundManagerProvider creates a provider with the given managers.

func (*MockBackgroundManagerProvider) GetBackgroundManager

func (p *MockBackgroundManagerProvider) GetBackgroundManager(sensorID string) BackgroundManagerInterface

GetBackgroundManager returns a mock manager for the sensor ID.

type MockDataSourceManager

type MockDataSourceManager struct {

	// Error injection
	StartLiveError error
	StopLiveError  error
	StartPCAPError error
	StopPCAPError  error

	// Call tracking
	StartLiveCalls int
	StopLiveCalls  int
	StartPCAPCalls int
	StopPCAPCalls  int

	// Context tracking
	LastLiveCtx context.Context
	LastPCAPCtx context.Context
	// contains filtered or unexported fields
}

MockDataSourceManager implements DataSourceManager for testing.

func NewMockDataSourceManager

func NewMockDataSourceManager() *MockDataSourceManager

NewMockDataSourceManager creates a new MockDataSourceManager.

func (*MockDataSourceManager) CurrentPCAPFile

func (m *MockDataSourceManager) CurrentPCAPFile() string

CurrentPCAPFile returns the current PCAP file.

func (*MockDataSourceManager) CurrentSource

func (m *MockDataSourceManager) CurrentSource() DataSource

CurrentSource returns the current data source.

func (*MockDataSourceManager) GetLastPCAPConfig

func (m *MockDataSourceManager) GetLastPCAPConfig() ReplayConfig

GetLastPCAPConfig returns the last PCAP config used.

func (*MockDataSourceManager) IsLiveStarted

func (m *MockDataSourceManager) IsLiveStarted() bool

IsLiveStarted returns true if live listener is running.

func (*MockDataSourceManager) IsPCAPInProgress

func (m *MockDataSourceManager) IsPCAPInProgress() bool

IsPCAPInProgress returns true if PCAP replay is active.

func (*MockDataSourceManager) Reset

func (m *MockDataSourceManager) Reset()

Reset resets the mock state.

func (*MockDataSourceManager) SetSource

func (m *MockDataSourceManager) SetSource(source DataSource)

SetSource sets the current source (for testing state setup).

func (*MockDataSourceManager) StartLiveListener

func (m *MockDataSourceManager) StartLiveListener(ctx context.Context) error

StartLiveListener starts the mock live listener.

func (*MockDataSourceManager) StartPCAPReplay

func (m *MockDataSourceManager) StartPCAPReplay(ctx context.Context, file string, config ReplayConfig) error

StartPCAPReplay starts mock PCAP replay.

func (*MockDataSourceManager) StopLiveListener

func (m *MockDataSourceManager) StopLiveListener() error

StopLiveListener stops the mock live listener.

func (*MockDataSourceManager) StopPCAPReplay

func (m *MockDataSourceManager) StopPCAPReplay() error

StopPCAPReplay stops mock PCAP replay.

type ObservationResponse

type ObservationResponse struct {
	TrackID     string   `json:"track_id"`
	Timestamp   string   `json:"timestamp"`
	Position    Position `json:"position"`
	Velocity    Velocity `json:"velocity"`
	SpeedMps    float32  `json:"speed_mps"`
	HeadingRad  float32  `json:"heading_rad"`
	BoundingBox struct {
		Length float32 `json:"length"`
		Width  float32 `json:"width"`
		Height float32 `json:"height"`
	} `json:"bounding_box"`
	HeightP95     float32 `json:"height_p95"`
	IntensityMean float32 `json:"intensity_mean"`
}

ObservationResponse represents a raw observation for overlaying foreground objects.

type ObservationsListResponse

type ObservationsListResponse struct {
	Observations []ObservationResponse `json:"observations"`
	Count        int                   `json:"count"`
	Timestamp    string                `json:"timestamp"`
}

ObservationsListResponse is the JSON response for observation overlays.

type OverallSummary

type OverallSummary = l8analytics.TrackOverallSummary

OverallSummary is a type alias for l8analytics.TrackOverallSummary.

type PCAPReplayConfig

type PCAPReplayConfig struct {
	PCAPFile        string
	StartSeconds    float64
	DurationSeconds float64
	MaxRetries      int
	AnalysisMode    bool    // When true, preserve grid after PCAP completion
	SpeedMode       string  // "analysis", "realtime", or "scaled"
	SpeedRatio      float64 // Multiplier for "scaled" mode (e.g. 0.5 = half speed)
}

PCAPReplayConfig holds configuration for starting a PCAP replay.

type PacketStats

type PacketStats struct {
	// contains filtered or unexported fields
}

PacketStats tracks packet statistics with thread-safe operations

func NewPacketStats

func NewPacketStats() *PacketStats

NewPacketStats creates a new PacketStats instance

func (*PacketStats) AddDropped

func (ps *PacketStats) AddDropped()

AddDropped increments dropped packet count

func (*PacketStats) AddPacket

func (ps *PacketStats) AddPacket(bytes int)

AddPacket increments packet count and byte count

func (*PacketStats) AddPoints

func (ps *PacketStats) AddPoints(count int)

AddPoints increments parsed point count

func (*PacketStats) GetAndReset

func (ps *PacketStats) GetAndReset() (packets int64, bytes int64, dropped int64, points int64, duration time.Duration)

GetAndReset returns current stats and resets counters

func (*PacketStats) GetLatestSnapshot

func (ps *PacketStats) GetLatestSnapshot() *StatsSnapshot

GetLatestSnapshot returns the most recent stats snapshot for web interface

func (*PacketStats) GetUptime

func (ps *PacketStats) GetUptime() time.Duration

GetUptime returns the time since the stats were created

func (*PacketStats) LogStats

func (ps *PacketStats) LogStats(parsePackets bool)

LogStats logs formatted statistics and stores snapshot for web interface

type ParamDef

type ParamDef struct {
	Key    string      // JSON key
	Label  string      // Display label
	Value  interface{} // Current value
	Format string      // Printf format string (optional)
}

ParamDef defines a configuration parameter for display and editing

type PcapFileInfo

type PcapFileInfo struct {
	Path       string `json:"path"`
	SizeBytes  int64  `json:"size_bytes"`
	ModifiedAt string `json:"modified_at"`
	InUse      bool   `json:"in_use"`
}

PcapFileInfo describes a single PCAP file found in the safe directory.

type PlaybackStatusInfo

type PlaybackStatusInfo struct {
	Mode         string  `json:"mode"` // "live", "pcap", "vrlog"
	Paused       bool    `json:"paused"`
	Rate         float32 `json:"rate"`
	Seekable     bool    `json:"seekable"`
	CurrentFrame uint64  `json:"current_frame"`
	TotalFrames  uint64  `json:"total_frames"`
	TimestampNs  int64   `json:"timestamp_ns"`
	LogStartNs   int64   `json:"log_start_ns"`
	LogEndNs     int64   `json:"log_end_ns"`
	VRLogPath    string  `json:"vrlog_path,omitempty"`
}

PlaybackStatusInfo represents the current playback state for API responses.

type Position

type Position struct {
	X float32 `json:"x"`
	Y float32 `json:"y"`
	Z float32 `json:"z"`
}

Position represents a 3D position in world coordinates.

type RealDataSourceManager

type RealDataSourceManager struct {
	// contains filtered or unexported fields
}

RealDataSourceManager implements DataSourceManager using Server operations.

func NewRealDataSourceManager

func NewRealDataSourceManager(ops ServerDataSourceOperations) *RealDataSourceManager

NewRealDataSourceManager creates a new RealDataSourceManager.

func (*RealDataSourceManager) CurrentPCAPFile

func (r *RealDataSourceManager) CurrentPCAPFile() string

CurrentPCAPFile returns the currently replaying PCAP file.

func (*RealDataSourceManager) CurrentSource

func (r *RealDataSourceManager) CurrentSource() DataSource

CurrentSource returns the currently active data source.

func (*RealDataSourceManager) IsPCAPInProgress

func (r *RealDataSourceManager) IsPCAPInProgress() bool

IsPCAPInProgress returns true if PCAP replay is currently active.

func (*RealDataSourceManager) SetPCAPState

func (r *RealDataSourceManager) SetPCAPState(inProgress bool, file string)

SetPCAPState sets the PCAP state (used internally by Server).

func (*RealDataSourceManager) SetSource

func (r *RealDataSourceManager) SetSource(source DataSource)

SetSource sets the current source (used internally by Server).

func (*RealDataSourceManager) StartLiveListener

func (r *RealDataSourceManager) StartLiveListener(ctx context.Context) error

StartLiveListener starts the live UDP listener.

func (*RealDataSourceManager) StartPCAPReplay

func (r *RealDataSourceManager) StartPCAPReplay(ctx context.Context, file string, config ReplayConfig) error

StartPCAPReplay starts replaying packets from a PCAP file.

func (*RealDataSourceManager) StopLiveListener

func (r *RealDataSourceManager) StopLiveListener() error

StopLiveListener stops the live UDP listener.

func (*RealDataSourceManager) StopPCAPReplay

func (r *RealDataSourceManager) StopPCAPReplay() error

StopPCAPReplay stops the current PCAP replay.

type ReplayConfig

type ReplayConfig struct {
	StartSeconds        float64         // Start offset in seconds
	DurationSeconds     float64         // Duration to replay (-1 for entire file)
	SpeedMode           string          // "realtime", "analysis", or "scaled"
	SpeedRatio          float64         // Speed multiplier (e.g., 2.0 = 2x speed)
	AnalysisMode        bool            // When true, preserve grid after completion
	DisableRecording    bool            // When true, skip VRLOG recording during PCAP replay
	SensorID            string          // Optional sensor override for analysis-run provenance
	PreferredRunID      string          // Optional caller-supplied run identifier
	ParentRunID         string          // Optional lineage for reprocess runs
	ReplayCaseID        string          // Optional source replay case for scene replays
	RequestedParamSetID string          // Optional existing launch-intent lineage
	RequestedParamsJSON json.RawMessage // Optional launch-intent parameters for provenance

	// Debug parameters
	DebugRingMin int
	DebugRingMax int
	DebugAzMin   float32
	DebugAzMax   float32
	EnableDebug  bool
	EnablePlots  bool
}

ReplayConfig contains configuration for PCAP replay.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server handles the HTTP interface for monitoring LiDAR statistics It provides endpoints for health checks and real-time status information

func NewServer

func NewServer(config Config) *Server

NewServer creates a new web server with the provided configuration

func (*Server) BaseContext

func (ws *Server) BaseContext() context.Context

BaseContext returns the base context for operations.

func (*Server) BenchmarkMode

func (ws *Server) BenchmarkMode() *atomic.Bool

BenchmarkMode returns a pointer to the atomic.Bool controlling pipeline performance tracing. The caller can pass this to TrackingPipelineConfig so benchmark logging is toggled at runtime via the dashboard checkbox.

func (*Server) Close

func (ws *Server) Close() error

Close shuts down the web server

func (*Server) CurrentPCAPFile

func (ws *Server) CurrentPCAPFile() string

CurrentPCAPFile returns the path of the active PCAP file (empty if none).

func (*Server) CurrentSource

func (ws *Server) CurrentSource() DataSource

CurrentSource returns the active data source type.

func (*Server) DisableTrackPersistenceFlag

func (ws *Server) DisableTrackPersistenceFlag() *atomic.Bool

DisableTrackPersistenceFlag returns a pointer to the atomic.Bool that suppresses DB track/observation writes. Wire this into TrackingPipelineConfig.DisableTrackPersistence so analysis replays and parameter sweeps do not pollute the production track store.

func (*Server) GetCurrentPCAPFile

func (ws *Server) GetCurrentPCAPFile() string

GetCurrentPCAPFile returns the current PCAP file being replayed.

func (*Server) GetCurrentSource

func (ws *Server) GetCurrentSource() DataSource

GetCurrentSource returns the currently active data source.

func (*Server) IsPCAPInProgress

func (ws *Server) IsPCAPInProgress() bool

IsPCAPInProgress returns true if PCAP replay is currently active.

func (*Server) LastAnalysisRunID

func (ws *Server) LastAnalysisRunID() string

LastAnalysisRunID returns the run ID set during the most recent PCAP replay in analysis mode.

func (*Server) PCAPDone

func (ws *Server) PCAPDone() <-chan struct{}

PCAPDone returns a channel that is closed when the current PCAP replay finishes, or nil if no replay is in progress. The caller must not close the returned channel.

func (*Server) PCAPSpeedRatio

func (ws *Server) PCAPSpeedRatio() float64

PCAPSpeedRatio returns the configured PCAP playback speed ratio.

func (*Server) RegisterRoutes

func (ws *Server) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers all Lidar monitor routes on the provided mux

func (*Server) ResetAllStateDirect

func (ws *Server) ResetAllStateDirect() error

ResetAllStateDirect exposes the internal resetAllState for in-process callers.

func (*Server) SetAutoTuneRunner

func (ws *Server) SetAutoTuneRunner(runner AutoTuneRunner)

SetAutoTuneRunner sets the auto-tune runner for web-triggered auto-tuning.

func (*Server) SetClassifier

func (ws *Server) SetClassifier(classifier *l6objects.TrackClassifier)

SetClassifier sets the classifier reference used by the tracking pipeline. This allows live updates of classification thresholds through /api/lidar/params.

func (*Server) SetHINTRunner

func (ws *Server) SetHINTRunner(runner HINTRunner)

SetHINTRunner sets the HINT runner for human-in-the-loop parameter tuning.

func (*Server) SetSweepRunner

func (ws *Server) SetSweepRunner(runner SweepRunner)

SetSweepRunner sets the sweep runner for web-triggered parameter sweeps.

func (*Server) SetSweepStore

func (ws *Server) SetSweepStore(store *sqlite.SweepStore)

SetSweepStore sets the sweep store for persisting sweep results.

func (*Server) SetTracker

func (ws *Server) SetTracker(tracker *l5tracks.Tracker)

SetTracker sets the tracker reference for direct config access via /api/lidar/params. Also propagates to trackAPI if available.

func (*Server) Start

func (ws *Server) Start(ctx context.Context) error

Start begins the HTTP server in a goroutine and handles graceful shutdown

func (*Server) StartLiveListener

func (ws *Server) StartLiveListener(ctx context.Context) error

StartLiveListener starts the live UDP listener via DataSourceManager.

func (*Server) StartLiveListenerInternal

func (ws *Server) StartLiveListenerInternal(ctx context.Context) error

StartLiveListenerInternal starts the UDP listener (called by RealDataSourceManager).

func (*Server) StartPCAPForSweep

func (ws *Server) StartPCAPForSweep(pcapFile string, analysisMode bool, speedMode string, speedRatio float64,
	startSeconds, durationSeconds float64, maxRetries int, disableRecording bool) error

StartPCAPForSweep starts a PCAP replay suitable for sweep use. It stops the live listener, resets all state (grid, frame builder, tracker), and begins the replay. It retries on conflict (another PCAP in progress) up to maxRetries times with 5-second delays.

func (*Server) StartPCAPInternal

func (ws *Server) StartPCAPInternal(pcapFile string, config ReplayConfig) error

StartPCAPInternal starts PCAP replay (called by RealDataSourceManager).

func (*Server) StopLiveListener

func (ws *Server) StopLiveListener() error

StopLiveListener stops the live UDP listener via DataSourceManager.

func (*Server) StopLiveListenerInternal

func (ws *Server) StopLiveListenerInternal()

StopLiveListenerInternal stops the UDP listener (called by RealDataSourceManager).

func (*Server) StopPCAPForSweep

func (ws *Server) StopPCAPForSweep() error

StopPCAPForSweep cancels any running PCAP replay and restores live mode.

func (*Server) StopPCAPInternal

func (ws *Server) StopPCAPInternal()

StopPCAPInternal stops the current PCAP replay (called by RealDataSourceManager).

type ServerDataSourceOperations

type ServerDataSourceOperations interface {
	// StartLiveListenerInternal starts the UDP listener.
	StartLiveListenerInternal(ctx context.Context) error
	// StopLiveListenerInternal stops the UDP listener.
	StopLiveListenerInternal()
	// StartPCAPInternal starts PCAP replay with the given configuration.
	StartPCAPInternal(pcapFile string, config ReplayConfig) error
	// StopPCAPInternal stops the current PCAP replay.
	StopPCAPInternal()
	// BaseContext returns the base context for operations.
	BaseContext() context.Context
}

ServerDataSourceOperations defines the interface for Server operations that the RealDataSourceManager needs to delegate to. This allows the DataSourceManager to call back into Server without circular dependencies.

type StatsSnapshot

type StatsSnapshot = l9endpoints.StatsSnapshot

StatsSnapshot is a type alias for l9endpoints.StatsSnapshot.

type SweepRunner

type SweepRunner interface {
	Start(ctx context.Context, req interface{}) error
	GetState() interface{}
	Stop()
}

SweepRunner defines the interface for parameter sweep operations. This interface allows the monitor package to work with sweep runners without importing the sweep package, avoiding import cycles.

type TrackAPI

type TrackAPI struct {
	// contains filtered or unexported fields
}

TrackAPI provides HTTP handlers for track-related endpoints. It supports both in-memory tracker queries and database persistence.

func NewTrackAPI

func NewTrackAPI(db *sqlite.SQLDB, sensorID string) *TrackAPI

NewTrackAPI creates a new TrackAPI instance.

func (*TrackAPI) SetTracker

func (api *TrackAPI) SetTracker(tracker *l5tracks.Tracker)

SetTracker sets the in-memory tracker for real-time queries.

type TrackPointResponse

type TrackPointResponse struct {
	X         float32 `json:"x"`
	Y         float32 `json:"y"`
	Timestamp string  `json:"timestamp"`
}

TrackPointResponse represents a point in a track's history.

type TrackResponse

type TrackResponse struct {
	TrackID             string               `json:"track_id"`
	SensorID            string               `json:"sensor_id"`
	State               string               `json:"state"`
	Position            Position             `json:"position"`
	Velocity            Velocity             `json:"velocity"`
	SpeedMps            float32              `json:"speed_mps"`
	HeadingRad          float32              `json:"heading_rad"`
	ObjectClass         string               `json:"object_class,omitempty"`
	ObjectConfidence    float32              `json:"object_confidence,omitempty"`
	ClassificationModel string               `json:"classification_model,omitempty"`
	ObservationCount    int                  `json:"observation_count"`
	AgeSeconds          float64              `json:"age_seconds"`
	AvgSpeedMps         float32              `json:"avg_speed_mps"`
	MaxSpeedMps         float32              `json:"max_speed_mps"`
	BoundingBox         BBox                 `json:"bounding_box"`
	OBBHeadingRad       float32              `json:"obb_heading_rad"`
	HeadingSource       int                  `json:"heading_source,omitempty"` // 0=PCA, 1=velocity, 2=displacement, 3=locked
	FirstSeen           string               `json:"first_seen"`
	LastSeen            string               `json:"last_seen"`
	History             []TrackPointResponse `json:"history,omitempty"`
}

TrackResponse represents a track in JSON API responses.

type TrackSummaryResponse

type TrackSummaryResponse struct {
	SensorID  string                  `json:"sensor_id"`
	StartTime string                  `json:"start_time,omitempty"`
	EndTime   string                  `json:"end_time,omitempty"`
	ByClass   map[string]ClassSummary `json:"by_class"`
	ByState   map[string]int          `json:"by_state"`
	Overall   OverallSummary          `json:"overall"`
	Timestamp string                  `json:"timestamp"`
}

TrackSummaryResponse is the JSON response for track summary statistics.

type TrackingParams

type TrackingParams struct {
	GatingDistanceSquared *float64
	ProcessNoisePos       *float64
	ProcessNoiseVel       *float64
	MeasurementNoise      *float64
}

TrackingParams holds tracker configuration values for sweep operations. Only non-nil fields will be updated on the server. Serialises as nested JSON: {"l5":{"cv_kf_v1":{...}}}.

func (TrackingParams) MarshalJSON

func (p TrackingParams) MarshalJSON() ([]byte, error)

MarshalJSON produces nested JSON, omitting nil fields.

func (*TrackingParams) UnmarshalJSON

func (p *TrackingParams) UnmarshalJSON(data []byte) error

UnmarshalJSON reads nested JSON: {"l5":{"cv_kf_v1":{...}}}.

type TracksListResponse

type TracksListResponse struct {
	Tracks    []TrackResponse `json:"tracks"`
	Count     int             `json:"count"`
	Timestamp string          `json:"timestamp"`
}

TracksListResponse is the JSON response for listing tracks.

type UpdateSceneRequest

type UpdateSceneRequest struct {
	Description       *string          `json:"description,omitempty"`
	ReferenceRunID    *string          `json:"reference_run_id,omitempty"`
	OptimalParamsJSON *json.RawMessage `json:"optimal_params_json,omitempty"`
	PCAPStartSecs     *float64         `json:"pcap_start_secs,omitempty"`
	PCAPDurationSecs  *float64         `json:"pcap_duration_secs,omitempty"`
}

UpdateSceneRequest is the request body for updating a scene.

type Velocity

type Velocity struct {
	VX float32 `json:"vx"`
	VY float32 `json:"vy"`
}

Velocity represents 2D velocity in world coordinates.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL