generated from thinkode/modelRepository
add MIDI discovery, connection and events
This commit is contained in:
5
app.go
5
app.go
@@ -30,9 +30,10 @@ type App struct {
|
||||
func NewApp() *App {
|
||||
// Create a new hadware manager
|
||||
hardwareManager := hardware.NewHardwareManager()
|
||||
// hardwareManager.RegisterFinder(hardware.NewMIDIFinder(5 * time.Second))
|
||||
hardwareManager.RegisterFinder(hardware.NewFTDIFinder(5 * time.Second))
|
||||
hardwareManager.RegisterFinder(hardware.NewFTDIFinder(3 * time.Second))
|
||||
hardwareManager.RegisterFinder(hardware.NewOS2LFinder())
|
||||
hardwareManager.RegisterFinder(hardware.NewMIDIFinder(3 * time.Second))
|
||||
|
||||
return &App{
|
||||
hardwareManager: hardwareManager,
|
||||
projectSave: "",
|
||||
|
||||
3
go.mod
3
go.mod
@@ -5,10 +5,11 @@ go 1.21
|
||||
toolchain go1.21.3
|
||||
|
||||
require (
|
||||
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/rs/zerolog v1.33.0
|
||||
github.com/wailsapp/wails/v2 v2.9.1
|
||||
gitlab.com/gomidi/midi v1.23.7
|
||||
gitlab.com/gomidi/rtmididrv v0.15.0
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
)
|
||||
|
||||
|
||||
7
go.sum
7
go.sum
@@ -37,8 +37,6 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79 h1:CA1UHN3RuY70DlC0RlvgtB1e8h3kYzmvK7s8CFe+Ohw=
|
||||
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79/go.mod h1:oBuZjmjlKSj9CZKrNhcx/adNhHiiE0hZknECjIP8Z0Q=
|
||||
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=
|
||||
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
@@ -70,6 +68,11 @@ github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhw
|
||||
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
|
||||
github.com/wailsapp/wails/v2 v2.9.1 h1:irsXnoQrCpeKzKTYZ2SUVlRRyeMR6I0vCO9Q1cvlEdc=
|
||||
github.com/wailsapp/wails/v2 v2.9.1/go.mod h1:7maJV2h+Egl11Ak8QZN/jlGLj2wg05bsQS+ywJPT0gI=
|
||||
gitlab.com/gomidi/midi v1.21.0/go.mod h1:3ohtNOhqoSakkuLG/Li1OI6I3J1c2LErnJF5o/VBq1c=
|
||||
gitlab.com/gomidi/midi v1.23.7 h1:I6qKoIk9s9dcX+pNf0jC+tziCzJFn82bMpuntRkLeik=
|
||||
gitlab.com/gomidi/midi v1.23.7/go.mod h1:3ohtNOhqoSakkuLG/Li1OI6I3J1c2LErnJF5o/VBq1c=
|
||||
gitlab.com/gomidi/rtmididrv v0.15.0 h1:52Heco8Y3Jjcl4t0yDUVikOxfI8FMF1Zq+qsG++TUeo=
|
||||
gitlab.com/gomidi/rtmididrv v0.15.0/go.mod h1:p/6IL1LGgj7utcv3wXudsDWiD9spgAdn0O8LDsGIPG0=
|
||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc=
|
||||
|
||||
@@ -172,7 +172,6 @@ func (f *FTDIFinder) GetPeripheralSettings(peripheralID string) (map[string]inte
|
||||
}
|
||||
return nil, fmt.Errorf("unable to found the peripheral")
|
||||
}
|
||||
log.Debug().Str("file", "FTDIFinder").Str("peripheralID", peripheralID).Msg("peripheral found by the FTDI finder")
|
||||
return peripheral.GetSettings(), nil
|
||||
}
|
||||
|
||||
@@ -181,8 +180,7 @@ func (f *FTDIFinder) SetPeripheralSettings(ctx context.Context, peripheralID str
|
||||
// Return the specified peripheral
|
||||
peripheral, found := f.detected[peripheralID]
|
||||
if !found {
|
||||
log.Error().Str("file", "FTDIFinder").Str("peripheralID", peripheralID).Msg("unable to get this peripheral from the FTDI finder")
|
||||
return fmt.Errorf("unable to found the peripheral")
|
||||
return fmt.Errorf("unable to found the FTDI peripheral")
|
||||
}
|
||||
log.Debug().Str("file", "FTDIFinder").Str("peripheralID", peripheralID).Msg("peripheral found by the FTDI finder")
|
||||
return peripheral.SetSettings(settings)
|
||||
|
||||
@@ -2,6 +2,7 @@ package hardware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -9,27 +10,45 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mattrtaylor/go-rtmidi"
|
||||
"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 {
|
||||
findTicker time.Ticker // Peripherals find ticker
|
||||
registeredPeripherals map[string]MIDIPeripheral // The list of peripherals
|
||||
scanChannel chan struct{} // The channel to trigger a scan event
|
||||
goWait sync.WaitGroup // Check goroutines execution
|
||||
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 DMXUSB protocol
|
||||
func NewMIDIFinder(findPeriod time.Duration) *MIDIFinder {
|
||||
// NewMIDIFinder creates a new MIDI finder
|
||||
func NewMIDIFinder(scanEvery time.Duration) *MIDIFinder {
|
||||
log.Trace().Str("file", "MIDIFinder").Msg("MIDI finder created")
|
||||
return &MIDIFinder{
|
||||
findTicker: *time.NewTicker(findPeriod),
|
||||
registeredPeripherals: make(map[string]MIDIPeripheral),
|
||||
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")
|
||||
@@ -38,44 +57,73 @@ func (f *MIDIFinder) Initialize() error {
|
||||
|
||||
// RegisterPeripheral registers a new peripheral
|
||||
func (f *MIDIFinder) RegisterPeripheral(ctx context.Context, peripheralData PeripheralInfo) (string, error) {
|
||||
peripheral, err := NewMIDIPeripheral(peripheralData)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("unable to create the MIDI peripheral: %v", err)
|
||||
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
|
||||
}
|
||||
}()
|
||||
}
|
||||
f.registeredPeripherals[peripheralData.SerialNumber] = *peripheral
|
||||
log.Trace().Any("periph", &peripheral).Str("file", "MIDIFinder").Str("peripheralName", peripheralData.Name).Msg("FTDI peripheral has been created")
|
||||
|
||||
// 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(peripheralID string) error {
|
||||
peripheral, registered := f.registeredPeripherals[peripheralID]
|
||||
if registered {
|
||||
err := peripheral.Disconnect()
|
||||
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 {
|
||||
return err
|
||||
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.registeredPeripherals, peripheralID)
|
||||
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.goWait.Add(1)
|
||||
f.wg.Add(1)
|
||||
go func() {
|
||||
defer f.goWait.Done()
|
||||
ticker := time.NewTicker(f.scanEvery)
|
||||
defer ticker.Stop()
|
||||
defer f.wg.Done()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-f.findTicker.C:
|
||||
// Scan the peripherals
|
||||
err := f.scanPeripherals(ctx)
|
||||
if err != nil {
|
||||
log.Err(err).Str("file", "MIDIFinder").Msg("unable to scan MIDI peripherals")
|
||||
}
|
||||
case <-f.scanChannel:
|
||||
case <-ticker.C:
|
||||
// Scan the peripherals
|
||||
err := f.scanPeripherals(ctx)
|
||||
if err != nil {
|
||||
@@ -87,13 +135,30 @@ func (f *MIDIFinder) Start(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop stops the finder
|
||||
func (f *MIDIFinder) Stop() error {
|
||||
// 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.goWait.Wait()
|
||||
// Stop the ticker
|
||||
f.findTicker.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
|
||||
}
|
||||
@@ -106,24 +171,25 @@ func (f *MIDIFinder) GetName() string {
|
||||
// GetPeripheralSettings gets the peripheral settings
|
||||
func (f *MIDIFinder) GetPeripheralSettings(peripheralID string) (map[string]interface{}, error) {
|
||||
// Return the specified peripheral
|
||||
peripheral, found := f.registeredPeripherals[peripheralID]
|
||||
peripheral, found := f.detected[peripheralID]
|
||||
if !found {
|
||||
log.Error().Str("file", "MIDIFinder").Str("peripheralID", peripheralID).Msg("unable to get this peripheral from the FTDI finder")
|
||||
// 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")
|
||||
}
|
||||
log.Debug().Str("file", "MIDIFinder").Str("peripheralID", peripheralID).Msg("peripheral found by the FTDI finder")
|
||||
return peripheral.GetSettings(), nil
|
||||
}
|
||||
|
||||
// SetPeripheralSettings sets the peripheral settings
|
||||
func (f *MIDIFinder) SetPeripheralSettings(peripheralID string, settings map[string]interface{}) error {
|
||||
func (f *MIDIFinder) SetPeripheralSettings(ctx context.Context, peripheralID string, settings map[string]interface{}) error {
|
||||
// Return the specified peripheral
|
||||
peripheral, found := f.registeredPeripherals[peripheralID]
|
||||
peripheral, found := f.detected[peripheralID]
|
||||
if !found {
|
||||
log.Error().Str("file", "MIDIFinder").Str("peripheralID", peripheralID).Msg("unable to get this peripheral from the FTDI finder")
|
||||
return fmt.Errorf("unable to found the peripheral")
|
||||
return fmt.Errorf("unable to found the MIDI peripheral")
|
||||
}
|
||||
log.Debug().Str("file", "MIDIFinder").Str("peripheralID", peripheralID).Msg("peripheral found by the FTDI finder")
|
||||
log.Debug().Str("file", "MIDIFinder").Str("peripheralID", peripheralID).Msg("peripheral found by the MIDI finder")
|
||||
return peripheral.SetSettings(settings)
|
||||
}
|
||||
|
||||
@@ -150,61 +216,168 @@ func splitStringAndNumber(input string) (string, int, error) {
|
||||
|
||||
// ForceScan explicily asks for scanning peripherals
|
||||
func (f *MIDIFinder) ForceScan() {
|
||||
f.scanChannel <- struct{}{}
|
||||
// f.scanChannel <- struct{}{}
|
||||
}
|
||||
|
||||
// scanPeripherals scans the MIDI peripherals
|
||||
func (f *MIDIFinder) scanPeripherals(ctx context.Context) error {
|
||||
// midiPeripherals := make(map[string]Peripheral)
|
||||
log.Trace().Str("file", "MIDIFinder").Msg("opening MIDI scanner port...")
|
||||
midiScanner, err := rtmidi.NewMIDIInDefault()
|
||||
currentMap := make(map[string]*MIDIPeripheral)
|
||||
|
||||
drv, err := rtmididrv.New()
|
||||
if err != nil {
|
||||
log.Err(err).Str("file", "MIDIFinder").Msg("unable to open the MIDI scanner port...")
|
||||
return fmt.Errorf("unable to open the MIDI scanner: %s", err)
|
||||
return fmt.Errorf("unable to open the MIDI driver")
|
||||
}
|
||||
defer midiScanner.Close()
|
||||
midiScanner.SetCallback(func(m rtmidi.MIDIIn, b []byte, f float64) {})
|
||||
log.Trace().Str("file", "MIDIFinder").Msg("scanning MIDI peripherals...")
|
||||
devicesCount, err := midiScanner.PortCount()
|
||||
defer drv.Close()
|
||||
|
||||
// Get MIDI INPUT ports
|
||||
ins, err := drv.Ins()
|
||||
if err != nil {
|
||||
log.Err(err).Str("file", "MIDIFinder").Msg("unable to scan MIDI peripherals...")
|
||||
return fmt.Errorf("unable to scan MIDI peripherals: %s", err)
|
||||
return fmt.Errorf("unable to scan MIDI IN ports: %s", err)
|
||||
}
|
||||
for i := 0; i < devicesCount; i++ {
|
||||
portName, err := midiScanner.PortName(i)
|
||||
if err != nil {
|
||||
log.Warn().Str("file", "MIDIPeripheral").Msg("found peripheral without a correct name, set it to unknown")
|
||||
portName = "Unknown device 0"
|
||||
|
||||
for _, port := range ins {
|
||||
// Exclude microsoft wavetable from the list
|
||||
if strings.Contains(port.String(), "GS Wavetable") {
|
||||
continue
|
||||
}
|
||||
// Separate data
|
||||
name, location, err := splitStringAndNumber(portName)
|
||||
if err != nil {
|
||||
log.Err(err).Str("file", "MIDIFinder").Str("description", portName).Msg("invalid peripheral description")
|
||||
return fmt.Errorf("invalid pripheral description: %s", err)
|
||||
|
||||
baseName := normalizeName(port.String())
|
||||
|
||||
if _, ok := currentMap[baseName]; !ok {
|
||||
currentMap[baseName] = &MIDIPeripheral{
|
||||
info: PeripheralInfo{
|
||||
Name: baseName,
|
||||
SerialNumber: baseName,
|
||||
ProtocolName: "MIDI",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
currentMap[baseName].inputPorts = append(currentMap[baseName].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())
|
||||
|
||||
if _, ok := currentMap[baseName]; !ok {
|
||||
currentMap[baseName] = &MIDIPeripheral{
|
||||
info: PeripheralInfo{
|
||||
Name: baseName,
|
||||
SerialNumber: baseName,
|
||||
ProtocolName: "MIDI",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
currentMap[baseName].outputsPorts = append(currentMap[baseName].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())
|
||||
}
|
||||
}
|
||||
log.Info().Str("file", "MIDIFinder").Str("name", name).Int("location", location).Msg("MIDI peripheral found")
|
||||
// Add the peripheral to the temporary list
|
||||
// sn := strings.ToLower(strings.Replace(name, " ", "_", -1))
|
||||
// midiPeripherals[sn] = NewMIDIPeripheral(name, location, sn)
|
||||
}
|
||||
// Compare with the current peripherals to detect arrivals/removals
|
||||
// removedList, addedList := comparePeripherals(f.peripherals, midiPeripherals)
|
||||
// Emit the events
|
||||
// emitPeripheralsEvents(ctx, removedList, PeripheralRemoval)
|
||||
log.Info().Str("file", "MIDIFinder").Msg("MIDI remove list emitted to the front")
|
||||
// emitPeripheralsEvents(ctx, addedList, PeripheralArrival)
|
||||
log.Info().Str("file", "MIDIFinder").Msg("MIDI add list emitted to the front")
|
||||
// Store the new peripherals list
|
||||
// f.peripherals = midiPeripherals
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreatePeripheral is not implemented here
|
||||
func (f *MIDIFinder) CreatePeripheral(context.Context) (Peripheral, error) {
|
||||
return nil, 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, " ")
|
||||
}
|
||||
|
||||
// DeletePeripheral is not implemented here
|
||||
func (f *MIDIFinder) DeletePeripheral(serialNumber string) error {
|
||||
return nil
|
||||
}
|
||||
// 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)
|
||||
// }
|
||||
|
||||
@@ -2,43 +2,91 @@ package hardware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
"gitlab.com/gomidi/midi"
|
||||
)
|
||||
|
||||
// MIDIPeripheral contains the data of a MIDI peripheral
|
||||
type MIDIPeripheral struct {
|
||||
wg sync.WaitGroup
|
||||
|
||||
inputPorts []midi.In
|
||||
outputsPorts []midi.Out
|
||||
|
||||
info PeripheralInfo // The peripheral info
|
||||
location int // The location of the peripheral
|
||||
settings map[string]interface{} // The settings of the peripheral
|
||||
}
|
||||
|
||||
// NewMIDIPeripheral creates a new MIDI peripheral
|
||||
func NewMIDIPeripheral(peripheralData PeripheralInfo) (*MIDIPeripheral, error) {
|
||||
func NewMIDIPeripheral(peripheralData PeripheralInfo, inputs []midi.In, outputs []midi.Out) *MIDIPeripheral {
|
||||
log.Trace().Str("file", "MIDIPeripheral").Str("name", peripheralData.Name).Str("s/n", peripheralData.SerialNumber).Msg("MIDI peripheral created")
|
||||
return &MIDIPeripheral{
|
||||
info: peripheralData,
|
||||
settings: peripheralData.Settings,
|
||||
}, nil
|
||||
info: peripheralData,
|
||||
inputPorts: inputs,
|
||||
outputsPorts: outputs,
|
||||
settings: peripheralData.Settings,
|
||||
}
|
||||
}
|
||||
|
||||
// Connect connects the MIDI peripheral
|
||||
func (p *MIDIPeripheral) Connect(ctx context.Context) error {
|
||||
runtime.EventsEmit(ctx, string(PeripheralStatusUpdated), p.GetInfo(), PeripheralStatusConnecting)
|
||||
|
||||
// Open input ports
|
||||
for _, port := range p.inputPorts {
|
||||
err := port.Open()
|
||||
if err != nil {
|
||||
runtime.EventsEmit(ctx, string(PeripheralStatusUpdated), p.GetInfo(), PeripheralStatusDisconnected)
|
||||
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(PeripheralEventEmitted), 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(PeripheralStatusUpdated), p.GetInfo(), PeripheralStatusDeactivated)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Disconnect disconnects the MIDI peripheral
|
||||
func (p *MIDIPeripheral) Disconnect() error {
|
||||
func (p *MIDIPeripheral) 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(PeripheralStatusUpdated), p.GetInfo(), PeripheralStatusDisconnected)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Activate activates the MIDI peripheral
|
||||
func (p *MIDIPeripheral) Activate(ctx context.Context) error {
|
||||
runtime.EventsEmit(ctx, string(PeripheralStatusUpdated), p.GetInfo(), PeripheralStatusActivated)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Deactivate deactivates the MIDI peripheral
|
||||
func (p *MIDIPeripheral) Deactivate(ctx context.Context) error {
|
||||
runtime.EventsEmit(ctx, string(PeripheralStatusUpdated), p.GetInfo(), PeripheralStatusDeactivated)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -62,3 +110,11 @@ func (p *MIDIPeripheral) GetSettings() map[string]interface{} {
|
||||
func (p *MIDIPeripheral) GetInfo() PeripheralInfo {
|
||||
return p.info
|
||||
}
|
||||
|
||||
// WaitStop wait about the peripheral to close
|
||||
func (p *MIDIPeripheral) WaitStop() error {
|
||||
log.Info().Str("file", "MIDIPeripheral").Str("s/n", p.info.SerialNumber).Msg("waiting for MIDI peripheral to close...")
|
||||
p.wg.Wait()
|
||||
log.Info().Str("file", "MIDIPeripheral").Str("s/n", p.info.SerialNumber).Msg("MIDI peripheral closed!")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -139,7 +139,6 @@ func (f *OS2LFinder) GetPeripheralSettings(peripheralID string) (map[string]any,
|
||||
log.Error().Str("file", "OS2LFinder").Str("peripheralID", peripheralID).Msg("unable to get this peripheral from the OS2L finder")
|
||||
return nil, fmt.Errorf("unable to found the peripheral")
|
||||
}
|
||||
log.Debug().Str("file", "OS2LFinder").Str("peripheralID", peripheralID).Msg("peripheral found by the OS2L finder")
|
||||
return peripheral.GetSettings(), nil
|
||||
}
|
||||
|
||||
@@ -148,8 +147,7 @@ func (f *OS2LFinder) SetPeripheralSettings(ctx context.Context, peripheralID str
|
||||
// Return the specified peripheral
|
||||
peripheral, found := f.saved[peripheralID]
|
||||
if !found {
|
||||
log.Error().Str("file", "OS2LFinder").Str("peripheralID", peripheralID).Msg("unable to get this peripheral from the FTDI finder")
|
||||
return fmt.Errorf("unable to found the peripheral")
|
||||
return fmt.Errorf("unable to found the FTDI peripheral")
|
||||
}
|
||||
|
||||
// Set the peripheral settings
|
||||
|
||||
Reference in New Issue
Block a user