Files
dmxconnect/hardware/os2l/OS2LProvider.go

106 lines
2.8 KiB
Go
Raw Normal View History

package os2l
import (
"context"
"dmxconnect/hardware"
"fmt"
"math/rand"
"strings"
"sync"
"github.com/rs/zerolog/log"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// Provider represents how the protocol is defined
type Provider struct {
wg sync.WaitGroup
mu sync.Mutex
detected map[string]*Endpoint // The list of saved endpoints
onArrival func(context.Context, hardware.Endpoint) // When a endpoint arrives
onRemoval func(context.Context, hardware.Endpoint) // When a endpoint goes away
}
// NewProvider creates a new OS2L provider
func NewProvider() *Provider {
log.Trace().Str("file", "OS2LProvider").Msg("OS2L provider created")
return &Provider{
detected: make(map[string]*Endpoint),
}
}
// Initialize initializes the provider
func (f *Provider) Initialize() error {
log.Trace().Str("file", "OS2LProvider").Msg("OS2L provider initialized")
return nil
}
// OnArrival is the callback function when a new endpoint arrives
func (f *Provider) OnArrival(cb func(context.Context, hardware.Endpoint)) {
f.onArrival = cb
}
// OnRemoval if the callback when a endpoint goes away
func (f *Provider) OnRemoval(cb func(context.Context, hardware.Endpoint)) {
f.onRemoval = cb
}
// Create creates a new endpoint, based on the endpoint information (manually created)
func (f *Provider) Create(ctx context.Context, endpointInfo hardware.EndpointInfo) (hardware.EndpointInfo, error) {
// If the SerialNumber is empty, generate another one
if endpointInfo.SerialNumber == "" {
endpointInfo.SerialNumber = strings.ToUpper(fmt.Sprintf("%08x", rand.Intn(1<<32)))
}
// Create a new OS2L endpoint
endpoint, err := NewOS2LEndpoint(endpointInfo)
if err != nil {
return hardware.EndpointInfo{}, fmt.Errorf("unable to create the OS2L endpoint: %w", err)
}
// Set the event callback
endpoint.SetEventCallback(func(event any) {
runtime.EventsEmit(ctx, string(hardware.EndpointEventEmitted), endpointInfo.SerialNumber, event)
})
f.detected[endpointInfo.SerialNumber] = endpoint
if f.onArrival != nil {
f.onArrival(ctx, endpoint) // Ask to register the endpoint in the project
}
return endpointInfo, err
}
// Remove removes an existing endpoint (manually created)
func (f *Provider) Remove(ctx context.Context, endpoint hardware.Endpoint) error {
if f.onRemoval != nil {
f.onRemoval(ctx, endpoint)
}
delete(f.detected, endpoint.GetInfo().SerialNumber)
return nil
}
// GetName returns the name of the driver
func (f *Provider) GetName() string {
return "OS2L"
}
// Start starts the provider
func (f *Provider) Start(ctx context.Context) error {
// No endpoints to scan here
return nil
}
// WaitStop stops the provider
func (f *Provider) WaitStop() error {
log.Trace().Str("file", "OS2LProvider").Msg("stopping the OS2L provider...")
// Waiting internal tasks
f.wg.Wait()
log.Trace().Str("file", "OS2LProvider").Msg("OS2L provider stopped")
return nil
}