1## Copyright (C) 2019-2021 John Donoghue <john.donoghue@ieee.org>
2##
3## This program is free software: you can redistribute it and/or modify it
4## under the terms of the GNU General Public License as published by
5## the Free Software Foundation, either version 3 of the License, or
6## (at your option) any later version.
7##
8## This program is distributed in the hope that it will be useful, but
9## WITHOUT ANY WARRANTY; without even the implied warranty of
10## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11## GNU General Public License for more details.
12##
13## You should have received a copy of the GNU General Public License
14## along with this program.  If not, see
15## <https://www.gnu.org/licenses/>.
16
17## -*- texinfo -*-
18## @deftypefn {} {[@var{ctrlid}, @var{dev}] =} midiid ()
19## Scan for control messages from midi devices to get the id of the device
20##
21## Function will display a prompt for the user to move the midi control and return when
22## a control messages is detected or ctrl-C is pressed.
23##
24## @subsubheading Inputs
25## None
26##
27## @subsubheading Outputs
28## @var{ctrlid} - control id made from the controller channel * 1000 + controller number.@*
29## @var{dev} = name of the midi device the controller was detected on.
30##
31## @subsubheading Examples
32## Monitor midi devices for first moving controller
33## @example
34## @code {
35## [ctrlid, devname] = midiid()
36## }
37## @end example
38##
39## @seealso{mididevinfo, midicontrols}
40## @end deftypefn
41function [ctrlid, devname] = midiid ()
42  ctrlid = 0;
43  devname = "";
44
45  # get the input devices
46  devs = __mididevinfo__ ();
47  idx = find (arrayfun(@(x) strcmpi(x.Direction, "input"), devs));
48
49  devices = {};
50
51  unwind_protect
52    # open input devs
53    for i = idx
54      di = devs(i);
55      di.device = mididevice("input", di.Name);
56      devices{end+1} = di;
57    endfor
58
59    #  clear pending data
60    for i = 1:length(devices)
61      m = midireceive(devices{i}.device);
62      m = midireceive(devices{i}.device);
63    endfor
64
65    printf("Move the control you wish to identify; Press Ctrl-C to abort\n");
66    printf("Waiting for control message...\n");
67
68    # poll looking for control messages
69    while ctrlid == 0
70      for i = 1:length(devices)
71        mx = midireceive(devices{i}.device);
72        for j = 1:length(mx)
73          m = mx(j);
74          if strcmp(m.type, "ControlChange")
75            ctrlid = m.channel*1000 + double(m.msgbytes(2));
76            devname = devices{i}.Name;
77          endif
78        endfor
79      endfor
80      pause (0.1)
81    endwhile
82
83  unwind_protect_cleanup
84    clear devices
85  end_unwind_protect
86
87endfunction
88
89