Files
dmxconnect/hardware/MIDIFinder.go

248 lines
6.3 KiB
Go
Raw Normal View History

package hardware
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/rs/zerolog/log"
"gitlab.com/gomidi/rtmididrv"
)
// MIDIFinder represents how the protocol is defined
type MIDIFinder struct {
wg sync.WaitGroup
mu sync.Mutex
detected map[string]*MIDIPeripheral // Detected peripherals
scanEvery time.Duration // Scans peripherals periodically
2025-11-30 18:33:00 +01:00
onArrival func(context.Context, Peripheral) // When a peripheral arrives
onRemoval func(context.Context, Peripheral) // 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,
detected: make(map[string]*MIDIPeripheral),
}
}
// OnArrival is the callback function when a new peripheral arrives
2025-11-30 18:33:00 +01:00
func (f *MIDIFinder) OnArrival(cb func(context.Context, Peripheral)) {
f.onArrival = cb
}
// OnRemoval i the callback when a peripheral goes away
2025-11-29 17:42:42 +01:00
func (f *MIDIFinder) OnRemoval(cb func(context.Context, Peripheral)) {
f.onRemoval = cb
}
// Initialize initializes the MIDI driver
func (f *MIDIFinder) Initialize() error {
log.Trace().Str("file", "MIDIFinder").Msg("MIDI finder initialized")
return nil
}
2025-11-29 17:42:42 +01:00
// Create creates a new peripheral, based on the peripheral information (manually created)
2025-11-30 18:33:00 +01:00
func (f *MIDIFinder) Create(ctx context.Context, peripheralInfo PeripheralInfo) (PeripheralInfo, error) {
return PeripheralInfo{}, nil
2025-01-26 12:01:31 +01:00
}
2025-11-29 17:42:42 +01:00
// Remove removes an existing peripheral (manually created)
func (f *MIDIFinder) Remove(ctx context.Context, peripheral Peripheral) error {
2025-01-26 12:01:31 +01:00
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...")
// Wait for goroutines to stop
f.wg.Wait()
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"
}
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")
}
// 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())
2025-11-16 21:44:48 +01:00
sn := strings.ReplaceAll(strings.ToLower(baseName), " ", "_")
2025-11-16 21:44:48 +01:00
if _, ok := currentMap[sn]; !ok {
currentMap[sn] = &MIDIPeripheral{
info: PeripheralInfo{
Name: baseName,
2025-11-16 21:44:48 +01:00
SerialNumber: sn,
ProtocolName: "MIDI",
},
}
}
2025-11-16 21:44:48 +01:00
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())
2025-11-16 21:44:48 +01:00
sn := strings.ReplaceAll(strings.ToLower(baseName), " ", "_")
if _, ok := currentMap[sn]; !ok {
currentMap[sn] = &MIDIPeripheral{
info: PeripheralInfo{
Name: baseName,
2025-11-16 21:44:48 +01:00
SerialNumber: sn,
ProtocolName: "MIDI",
},
}
}
2025-11-16 21:44:48 +01:00
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 {
2025-11-30 18:33:00 +01:00
f.onArrival(ctx, discovery)
}
}
}
// Detect removals
for sn, oldPeripheral := range f.detected {
if _, still := currentMap[sn]; !still {
log.Info().Str("sn", sn).Str("name", oldPeripheral.GetInfo().Name).Msg("[MIDI] peripheral removed")
// Execute the removal callback
if f.onRemoval != nil {
2025-11-29 17:42:42 +01:00
f.onRemoval(ctx, oldPeripheral)
}
2025-11-29 17:42:42 +01:00
// Delete it from the detected list
delete(f.detected, sn)
}
}
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, " ")
}