fixed: create peripheral

This commit is contained in:
2025-11-30 18:33:00 +01:00
parent d1fda9f075
commit 7f60f7b8d7
8 changed files with 83 additions and 138 deletions

View File

@@ -18,41 +18,36 @@ type OS2LFinder struct {
detected map[string]*OS2LPeripheral // The list of saved peripherals
eventBus EventBus // The hardware event bus
onArrival func(context.Context, Peripheral, bool) // When a peripheral arrives
onArrival func(context.Context, Peripheral) // When a peripheral arrives
onRemoval func(context.Context, Peripheral) // When a peripheral goes away
}
// NewOS2LFinder creates a new OS2L finder
func NewOS2LFinder(eventBus EventBus) *OS2LFinder {
func NewOS2LFinder() *OS2LFinder {
log.Trace().Str("file", "OS2LFinder").Msg("OS2L finder created")
return &OS2LFinder{
detected: make(map[string]*OS2LPeripheral),
eventBus: eventBus,
}
}
// Initialize initializes the finder
func (f *OS2LFinder) Initialize() error {
// Subscribe to all OS2L peripherals that are added to the project
f.eventBus.SubscribeType(f.GetName(), f)
log.Trace().Str("file", "OS2LFinder").Msg("OS2L finder initialized")
return nil
}
// OnArrival is the callback function when a new peripheral arrives
func (f *OS2LFinder) OnArrival(cb func(context.Context, Peripheral, bool)) {
func (f *OS2LFinder) OnArrival(cb func(context.Context, Peripheral)) {
f.onArrival = cb
}
// OnRemoval i the callback when a peripheral goes away
// OnRemoval if the callback when a peripheral goes away
func (f *OS2LFinder) OnRemoval(cb func(context.Context, Peripheral)) {
f.onRemoval = cb
}
// Create creates a new peripheral, based on the peripheral information (manually created)
func (f *OS2LFinder) Create(ctx context.Context, peripheralInfo PeripheralInfo) error {
func (f *OS2LFinder) Create(ctx context.Context, peripheralInfo PeripheralInfo) (PeripheralInfo, error) {
// If the SerialNumber is empty, generate another one
if peripheralInfo.SerialNumber == "" {
peripheralInfo.SerialNumber = strings.ToUpper(fmt.Sprintf("%08x", rand.Intn(1<<32)))
@@ -61,7 +56,7 @@ func (f *OS2LFinder) Create(ctx context.Context, peripheralInfo PeripheralInfo)
// Create a new OS2L peripheral
peripheral, err := NewOS2LPeripheral(peripheralInfo)
if err != nil {
return fmt.Errorf("unable to create the OS2L peripheral: %w", err)
return PeripheralInfo{}, fmt.Errorf("unable to create the OS2L peripheral: %w", err)
}
// Set the event callback
@@ -72,9 +67,9 @@ func (f *OS2LFinder) Create(ctx context.Context, peripheralInfo PeripheralInfo)
f.detected[peripheralInfo.SerialNumber] = peripheral
if f.onArrival != nil {
f.onArrival(ctx, peripheral, true) // Ask to register the peripheral in the project
f.onArrival(ctx, peripheral) // Ask to register the peripheral in the project
}
return err
return peripheralInfo, err
}
// Remove removes an existing peripheral (manually created)