Closes #34 Implement MIDI peripherals
Implement device concept
Cleaning project

Reviewed-on: #35
This commit was merged in pull request #35.
This commit is contained in:
2025-12-02 18:02:17 +00:00
parent 932c288a9c
commit 4fbb75ad19
42 changed files with 1638 additions and 1564 deletions

View File

@@ -0,0 +1,140 @@
package genericmidi
import (
"context"
"dmxconnect/hardware"
"fmt"
"sync"
"github.com/rs/zerolog/log"
"github.com/wailsapp/wails/v2/pkg/runtime"
"gitlab.com/gomidi/midi"
)
// Device represents the device to control
type Device struct {
ID string // Device ID
Mapping hardware.MappingInfo // Device mapping configuration
}
// ------------------- //
// Endpoint contains the data of a MIDI endpoint
type Endpoint struct {
wg sync.WaitGroup
inputPorts []midi.In
outputsPorts []midi.Out
info hardware.EndpointInfo // The endpoint info
settings map[string]interface{} // The settings of the endpoint
devices []Device // All the MIDI devices that the endpoint can handle
}
// NewEndpoint creates a new MIDI endpoint
func NewEndpoint(endpointData hardware.EndpointInfo, inputs []midi.In, outputs []midi.Out) *Endpoint {
log.Trace().Str("file", "MIDIEndpoint").Str("name", endpointData.Name).Str("s/n", endpointData.SerialNumber).Msg("MIDI endpoint created")
return &Endpoint{
info: endpointData,
inputPorts: inputs,
outputsPorts: outputs,
settings: endpointData.Settings,
}
}
// SetDeviceArrivalCallback is called when we need to add a new device to the hardware
func (p *Endpoint) SetDeviceArrivalCallback(adc func(context.Context, hardware.DeviceInfo, hardware.Endpoint) error) {
}
// SetDeviceRemovalCallback is called when we need to remove a device from the hardware
func (p *Endpoint) SetDeviceRemovalCallback(rdc func(context.Context, string) error) {
}
// Connect connects the MIDI endpoint
func (p *Endpoint) Connect(ctx context.Context) error {
runtime.EventsEmit(ctx, string(hardware.EndpointStatusUpdated), p.GetInfo(), hardware.EndpointStatusConnecting)
// Open input ports
for _, port := range p.inputPorts {
err := port.Open()
if err != nil {
runtime.EventsEmit(ctx, string(hardware.EndpointStatusUpdated), p.GetInfo(), hardware.EndpointStatusDisconnected)
return fmt.Errorf("unable to open the MIDI IN port: %w", err)
}
port.SetListener(func(msg []byte, delta int64) {
// Emit the event to the front
runtime.EventsEmit(ctx, string(hardware.EndpointEventEmitted), p.info.SerialNumber, msg)
log.Debug().Str("message", string(msg)).Int64("delta", delta).Msg("message received")
})
log.Info().Str("name", port.String()).Msg("port open successfully")
}
p.wg.Add(1)
go func() {
defer p.wg.Done()
<-ctx.Done()
_ = p.Disconnect(ctx)
}()
runtime.EventsEmit(ctx, string(hardware.EndpointStatusUpdated), p.GetInfo(), hardware.EndpointStatusDeactivated)
return nil
}
// Disconnect disconnects the MIDI endpoint
func (p *Endpoint) Disconnect(ctx context.Context) error {
// Close all inputs ports
for _, port := range p.inputPorts {
err := port.Close()
if err != nil {
return fmt.Errorf("unable to close the MIDI IN port: %w", err)
}
}
runtime.EventsEmit(ctx, string(hardware.EndpointStatusUpdated), p.GetInfo(), hardware.EndpointStatusDisconnected)
return nil
}
// Activate activates the MIDI endpoint
func (p *Endpoint) Activate(ctx context.Context) error {
runtime.EventsEmit(ctx, string(hardware.EndpointStatusUpdated), p.GetInfo(), hardware.EndpointStatusActivated)
return nil
}
// Deactivate deactivates the MIDI endpoint
func (p *Endpoint) Deactivate(ctx context.Context) error {
runtime.EventsEmit(ctx, string(hardware.EndpointStatusUpdated), p.GetInfo(), hardware.EndpointStatusDeactivated)
return nil
}
// SetSettings sets a specific setting for this endpoint
func (p *Endpoint) SetSettings(ctx context.Context, settings map[string]any) error {
p.settings = settings
return nil
}
// SetDeviceProperty - not implemented for this kind of endpoint
func (p *Endpoint) SetDeviceProperty(context.Context, uint32, byte) error {
return nil
}
// GetSettings gets the endpoint settings
func (p *Endpoint) GetSettings() map[string]interface{} {
return p.settings
}
// GetInfo gets the endpoint information
func (p *Endpoint) GetInfo() hardware.EndpointInfo {
return p.info
}
// WaitStop wait about the endpoint to close
func (p *Endpoint) WaitStop() error {
log.Info().Str("file", "MIDIEndpoint").Str("s/n", p.info.SerialNumber).Msg("waiting for MIDI endpoint to close...")
p.wg.Wait()
log.Info().Str("file", "MIDIEndpoint").Str("s/n", p.info.SerialNumber).Msg("MIDI endpoint closed!")
return nil
}

View File

@@ -0,0 +1,248 @@
package genericmidi
import (
"context"
"dmxconnect/hardware"
"fmt"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/rs/zerolog/log"
"gitlab.com/gomidi/rtmididrv"
)
// Provider represents how the protocol is defined
type Provider struct {
wg sync.WaitGroup
mu sync.Mutex
detected map[string]*Endpoint // Detected endpoints
scanEvery time.Duration // Scans endpoints periodically
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 MIDI provider
func NewProvider(scanEvery time.Duration) *Provider {
log.Trace().Str("file", "MIDIProvider").Msg("MIDI provider created")
return &Provider{
scanEvery: scanEvery,
detected: make(map[string]*Endpoint),
}
}
// OnArrival is the callback function when a new endpoint arrives
func (f *Provider) OnArrival(cb func(context.Context, hardware.Endpoint)) {
f.onArrival = cb
}
// OnRemoval i the callback when a endpoint goes away
func (f *Provider) OnRemoval(cb func(context.Context, hardware.Endpoint)) {
f.onRemoval = cb
}
// Initialize initializes the MIDI driver
func (f *Provider) Initialize() error {
log.Trace().Str("file", "MIDIProvider").Msg("MIDI provider initialized")
return nil
}
// 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) {
return hardware.EndpointInfo{}, nil
}
// Remove removes an existing endpoint (manually created)
func (f *Provider) Remove(ctx context.Context, endpoint hardware.Endpoint) error {
return nil
}
// Start starts the provider and search for endpoints
func (f *Provider) 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 endpoints
err := f.scanEndpoints(ctx)
if err != nil {
log.Err(err).Str("file", "MIDIProvider").Msg("unable to scan MIDI endpoints")
}
}
}
}()
return nil
}
// WaitStop stops the provider
func (f *Provider) WaitStop() error {
log.Trace().Str("file", "MIDIProvider").Msg("stopping the MIDI provider...")
// Wait for goroutines to stop
f.wg.Wait()
log.Trace().Str("file", "MIDIProvider").Msg("MIDI provider stopped")
return nil
}
// GetName returns the name of the driver
func (f *Provider) 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")
}
// scanEndpoints scans the MIDI endpoints
func (f *Provider) scanEndpoints(ctx context.Context) error {
currentMap := make(map[string]*Endpoint)
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] = &Endpoint{
info: hardware.EndpointInfo{
Name: baseName,
SerialNumber: sn,
ProtocolName: "MIDI",
},
}
}
currentMap[sn].inputPorts = append(currentMap[sn].inputPorts, port)
log.Info().Any("endpoints", 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] = &Endpoint{
info: hardware.EndpointInfo{
Name: baseName,
SerialNumber: sn,
ProtocolName: "MIDI",
},
}
}
currentMap[sn].outputsPorts = append(currentMap[sn].outputsPorts, port)
log.Info().Any("endpoints", currentMap).Msg("available MIDI OUT ports")
}
log.Debug().Any("value", currentMap).Msg("MIDI endpoints map")
// Detect arrivals
for sn, discovery := range currentMap {
if _, known := f.detected[sn]; !known {
endpoint := NewEndpoint(discovery.info, discovery.inputPorts, discovery.outputsPorts)
f.detected[sn] = endpoint
if f.onArrival != nil {
f.onArrival(ctx, discovery)
}
}
}
// Detect removals
for sn, oldEndpoint := range f.detected {
if _, still := currentMap[sn]; !still {
log.Info().Str("sn", sn).Str("name", oldEndpoint.GetInfo().Name).Msg("[MIDI] endpoint removed")
// Execute the removal callback
if f.onRemoval != nil {
f.onRemoval(ctx, oldEndpoint)
}
// 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, " ")
}