package hardware import ( "context" "fmt" "math/rand" "strings" "sync" "github.com/rs/zerolog/log" "github.com/wailsapp/wails/v2/pkg/runtime" ) // OS2LProvider represents how the protocol is defined type OS2LProvider struct { wg sync.WaitGroup mu sync.Mutex detected map[string]*OS2LEndpoint // The list of saved endpoints onArrival func(context.Context, Endpoint) // When a endpoint arrives onRemoval func(context.Context, Endpoint) // When a endpoint goes away } // NewOS2LProvider creates a new OS2L provider func NewOS2LProvider() *OS2LProvider { log.Trace().Str("file", "OS2LProvider").Msg("OS2L provider created") return &OS2LProvider{ detected: make(map[string]*OS2LEndpoint), } } // Initialize initializes the provider func (f *OS2LProvider) 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 *OS2LProvider) OnArrival(cb func(context.Context, Endpoint)) { f.onArrival = cb } // OnRemoval if the callback when a endpoint goes away func (f *OS2LProvider) OnRemoval(cb func(context.Context, Endpoint)) { f.onRemoval = cb } // Create creates a new endpoint, based on the endpoint information (manually created) func (f *OS2LProvider) Create(ctx context.Context, endpointInfo EndpointInfo) (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 EndpointInfo{}, fmt.Errorf("unable to create the OS2L endpoint: %w", err) } // Set the event callback endpoint.SetEventCallback(func(event any) { runtime.EventsEmit(ctx, string(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 *OS2LProvider) Remove(ctx context.Context, endpoint 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 *OS2LProvider) GetName() string { return "OS2L" } // Start starts the provider func (f *OS2LProvider) Start(ctx context.Context) error { // No endpoints to scan here return nil } // WaitStop stops the provider func (f *OS2LProvider) 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 }