package hardware import ( "context" "errors" "fmt" "regexp" "strconv" "strings" "sync" "time" "github.com/rs/zerolog/log" "github.com/wailsapp/wails/v2/pkg/runtime" "gitlab.com/gomidi/rtmididrv" ) // MIDIFinder represents how the protocol is defined type MIDIFinder struct { wg sync.WaitGroup mu sync.Mutex saved map[string]PeripheralInfo // Peripherals saved in the project detected map[string]*MIDIPeripheral // Detected peripherals scanEvery time.Duration // Scans peripherals periodically onArrival func(p PeripheralInfo) // When a peripheral arrives onRemoval func(p PeripheralInfo) // When a peripheral goes away } // NewMIDIFinder creates a new MIDI finder func NewMIDIFinder(scanEvery time.Duration) *MIDIFinder { log.Trace().Str("file", "MIDIFinder").Msg("MIDI finder created") return &MIDIFinder{ scanEvery: scanEvery, saved: make(map[string]PeripheralInfo), detected: make(map[string]*MIDIPeripheral), } } // OnArrival is the callback function when a new peripheral arrives func (f *MIDIFinder) OnArrival(cb func(p PeripheralInfo)) { f.onArrival = cb } // OnRemoval i the callback when a peripheral goes away func (f *MIDIFinder) OnRemoval(cb func(p PeripheralInfo)) { f.onRemoval = cb } // Initialize initializes the MIDI driver func (f *MIDIFinder) Initialize() error { log.Trace().Str("file", "MIDIFinder").Msg("MIDI finder initialized") return nil } // RegisterPeripheral registers a new peripheral func (f *MIDIFinder) RegisterPeripheral(ctx context.Context, peripheralData PeripheralInfo) (string, error) { f.mu.Lock() defer f.mu.Unlock() f.saved[peripheralData.SerialNumber] = peripheralData runtime.EventsEmit(ctx, string(PeripheralStatusUpdated), peripheralData, PeripheralStatusDisconnected) // If already detected, connect it if peripheral, ok := f.detected[peripheralData.SerialNumber]; ok { f.wg.Add(1) go func() { defer f.wg.Done() err := peripheral.Connect(ctx) if err != nil { log.Err(err).Str("file", "FTDIFinder").Str("peripheralSN", peripheralData.SerialNumber).Msg("unable to connect the peripheral") return } // Peripheral connected, activate it err = peripheral.Activate(ctx) if err != nil { log.Err(err).Str("file", "FTDIFinder").Str("peripheralSN", peripheralData.SerialNumber).Msg("unable to activate the FTDI peripheral") return } }() } // Emits the event in the hardware runtime.EventsEmit(ctx, "LOAD_PERIPHERAL", peripheralData) return peripheralData.SerialNumber, nil } // UnregisterPeripheral unregisters an existing peripheral func (f *MIDIFinder) UnregisterPeripheral(ctx context.Context, peripheralData PeripheralInfo) error { f.mu.Lock() defer f.mu.Unlock() if peripheral, detected := f.detected[peripheralData.SerialNumber]; detected { // Deactivating peripheral err := peripheral.Deactivate(ctx) if err != nil { log.Err(err).Str("sn", peripheralData.SerialNumber).Msg("unable to deactivate the peripheral") return nil } // Disconnecting peripheral err = peripheral.Disconnect(ctx) if err != nil { log.Err(err).Str("sn", peripheralData.SerialNumber).Msg("unable to disconnect the peripheral") return nil } } delete(f.saved, peripheralData.SerialNumber) runtime.EventsEmit(ctx, "UNLOAD_PERIPHERAL", peripheralData) return nil } // Start starts the finder and search for peripherals func (f *MIDIFinder) Start(ctx context.Context) error { f.wg.Add(1) go func() { ticker := time.NewTicker(f.scanEvery) defer ticker.Stop() defer f.wg.Done() for { select { case <-ctx.Done(): return case <-ticker.C: // Scan the peripherals err := f.scanPeripherals(ctx) if err != nil { log.Err(err).Str("file", "MIDIFinder").Msg("unable to scan MIDI peripherals") } } } }() return nil } // WaitStop stops the finder func (f *MIDIFinder) WaitStop() error { log.Trace().Str("file", "MIDIFinder").Msg("stopping the MIDI finder...") // Close the channel // close(f.scanChannel) // Wait for all the peripherals to close log.Trace().Str("file", "MIDIFinder").Msg("closing all MIDI peripherals") var errs []error for registeredPeripheralSN, registeredPeripheral := range f.detected { err := registeredPeripheral.WaitStop() if err != nil { errs = append(errs, fmt.Errorf("%s: %w", registeredPeripheralSN, err)) } } // Wait for goroutines to stop f.wg.Wait() // Returning errors if len(errs) > 0 { return errors.Join(errs...) } log.Trace().Str("file", "MIDIFinder").Msg("MIDI finder stopped") return nil } // GetName returns the name of the driver func (f *MIDIFinder) GetName() string { return "MIDI" } // GetPeripheralSettings gets the peripheral settings func (f *MIDIFinder) GetPeripheralSettings(peripheralID string) (map[string]interface{}, error) { // Return the specified peripheral peripheral, found := f.detected[peripheralID] if !found { // FTDI not detected, return the last settings saved if savedPeripheral, isFound := f.saved[peripheralID]; isFound { return savedPeripheral.Settings, nil } return nil, fmt.Errorf("unable to found the peripheral") } return peripheral.GetSettings(), nil } // SetPeripheralSettings sets the peripheral settings func (f *MIDIFinder) SetPeripheralSettings(ctx context.Context, peripheralID string, settings map[string]interface{}) error { // Return the specified peripheral peripheral, found := f.detected[peripheralID] if !found { return fmt.Errorf("unable to found the MIDI peripheral") } log.Debug().Str("file", "MIDIFinder").Str("peripheralID", peripheralID).Msg("peripheral found by the MIDI finder") return peripheral.SetSettings(settings) } func splitStringAndNumber(input string) (string, int, error) { // Regular expression to match the text part and the number at the end re := regexp.MustCompile(`^(.*?)(\d+)$`) matches := re.FindStringSubmatch(input) // Check if the regex found both a text part and a number if len(matches) == 3 { // matches[1]: text part (might contain trailing spaces) // matches[2]: numeric part as a string textPart := strings.TrimSpace(matches[1]) // Remove any trailing spaces from the text numberPart, err := strconv.Atoi(matches[2]) if err != nil { return "", 0, err // Return error if the number conversion fails } return textPart, numberPart, nil } // Return an error if no trailing number is found return "", 0, fmt.Errorf("no number found at the end of the string") } // ForceScan explicily asks for scanning peripherals func (f *MIDIFinder) ForceScan() { // f.scanChannel <- struct{}{} } // scanPeripherals scans the MIDI peripherals func (f *MIDIFinder) scanPeripherals(ctx context.Context) error { currentMap := make(map[string]*MIDIPeripheral) drv, err := rtmididrv.New() if err != nil { return fmt.Errorf("unable to open the MIDI driver") } defer drv.Close() // Get MIDI INPUT ports ins, err := drv.Ins() if err != nil { return fmt.Errorf("unable to scan MIDI IN ports: %s", err) } for _, port := range ins { // Exclude microsoft wavetable from the list if strings.Contains(port.String(), "GS Wavetable") { continue } baseName := normalizeName(port.String()) sn := strings.ReplaceAll(strings.ToLower(baseName), " ", "_") if _, ok := currentMap[sn]; !ok { currentMap[sn] = &MIDIPeripheral{ info: PeripheralInfo{ Name: baseName, SerialNumber: sn, ProtocolName: "MIDI", }, } } currentMap[sn].inputPorts = append(currentMap[sn].inputPorts, port) log.Info().Any("peripherals", currentMap).Msg("available MIDI IN ports") } // Get MIDI OUTPUT ports outs, err := drv.Outs() if err != nil { return fmt.Errorf("unable to scan MIDI OUT ports: %s", err) } for _, port := range outs { // Exclude microsoft wavetable from the list if strings.Contains(port.String(), "GS Wavetable") { continue } baseName := normalizeName(port.String()) sn := strings.ReplaceAll(strings.ToLower(baseName), " ", "_") if _, ok := currentMap[sn]; !ok { currentMap[sn] = &MIDIPeripheral{ info: PeripheralInfo{ Name: baseName, SerialNumber: sn, ProtocolName: "MIDI", }, } } currentMap[sn].outputsPorts = append(currentMap[sn].outputsPorts, port) log.Info().Any("peripherals", currentMap).Msg("available MIDI OUT ports") } log.Debug().Any("value", currentMap).Msg("MIDI peripherals map") // Detect arrivals for sn, discovery := range currentMap { if _, known := f.detected[sn]; !known { peripheral := NewMIDIPeripheral(discovery.info, discovery.inputPorts, discovery.outputsPorts) f.detected[sn] = peripheral if f.onArrival != nil { f.onArrival(discovery.GetInfo()) } log.Info().Str("sn", sn).Str("name", discovery.GetInfo().SerialNumber).Msg("[MIDI] New peripheral detected") // If the peripheral is saved in the project => connect if _, saved := f.saved[sn]; saved { f.wg.Add(1) go func(p PeripheralInfo) { defer f.wg.Done() err := peripheral.Connect(ctx) if err != nil { log.Err(err).Str("sn", p.SerialNumber).Msg("unable to connect the MIDI peripheral") return } err = peripheral.Activate(ctx) if err != nil { log.Err(err).Str("sn", p.SerialNumber).Msg("unable to activate the MIDI peripheral") return } }(discovery.GetInfo()) } } } // Detect removals for sn, oldPeripheral := range f.detected { if _, still := currentMap[sn]; !still { // Properly clean the DMX device err := oldPeripheral.Deactivate(ctx) if err != nil { log.Err(err).Str("sn", sn).Msg("unable to deactivate the MIDI peripheral after disconnection") } err = oldPeripheral.Disconnect(ctx) if err != nil { log.Err(err).Str("sn", sn).Msg("unable to disconnect the MIDI peripheral after disconnection") } // Delete it from the detected list delete(f.detected, sn) log.Info().Str("sn", sn).Str("name", oldPeripheral.GetInfo().Name).Msg("[MIDI] peripheral removed") // Execute the removal callback if f.onRemoval != nil { f.onRemoval(oldPeripheral.GetInfo()) } } } return nil } func normalizeName(raw string) string { name := strings.TrimSpace(raw) // Si parenthèses, prendre le texte à l'intérieur start := strings.Index(name, "(") end := strings.LastIndex(name, ")") if start != -1 && end != -1 && start < end { name = name[start+1 : end] return strings.TrimSpace(name) } // Sinon, supprimer le dernier mot s'il est un entier parts := strings.Fields(name) // découpe en mots if len(parts) > 1 { if _, err := strconv.Atoi(parts[len(parts)-1]); err == nil { parts = parts[:len(parts)-1] // retirer le dernier mot } } return strings.Join(parts, " ") } // func normalizeName(name string) string { // // Cas communs : "MIDIIN2 (XXX)" → "XXX" // if strings.Contains(name, "(") && strings.Contains(name, ")") { // start := strings.Index(name, "(") // end := strings.Index(name, ")") // if start < end { // return strings.TrimSpace(name[start+1 : end]) // } // } // // Sinon, on retourne tel quel // return strings.TrimSpace(name) // }