1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
#include "connection_manager.h"
#include "device_connection.h"
#include "udevw/include/udevw.hpp"
#include <rtmidi/RtMidi.h>
#include <iostream>
#include <map>
namespace midi_router
{
static void
callback(double time_stamp, std::vector<unsigned char> *raw, void *user_data)
{
Device_Connection* device = static_cast<Device_Connection*>(user_data);
if (raw->size() > 3)
{
std::cerr << "Received message with wrong size (" << raw->size() << ") from " << device->source_id << ", dropping\n";
for (auto const & byte : *raw) std::cerr << static_cast<unsigned>(byte);
std::cerr << "\n";
return;
}
Message message { &device->source_id, *raw };
device->submitter.submit(message);
}
Connection_Manager::Connection_Manager(Device_Map const & device_map, Submitter & submitter):
m_device_map(device_map),
m_submitter(submitter),
m_connections{},
m_detector(std::bind(&Connection_Manager::detect_devices, this))
{
for (auto const & [name, id] : device_map)
{
m_connections[id] = std::make_unique<Device_Connection>(id, name, submitter, callback);
}
refresh_devices(true, false);
}
Connection_Manager::~Connection_Manager() = default;
Sender &
Connection_Manager::get_sender(Device_Id const & device) const
{
return *m_connections.at(device);
}
void
Connection_Manager::detect_devices()
{
auto udev = udevw::Udev::create();
auto monitor = udevw::Monitor::create_from_netlink(udev, "udev");
monitor.filter_add_match_subsystem("sound"); // devtype = nullptr implied
monitor.enable_receiving();
int fd = monitor.get_fd();
for (;;) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
if (select(fd +1, &fds, nullptr, nullptr, nullptr) > 0 && FD_ISSET(fd, &fds)) {
auto device = monitor.receive_device();
auto action = device.get_action();
if (!action) continue;
bool add = *action == "add";
bool remove = *action == "remove";
refresh_devices(add, remove);
}
}
}
void
Connection_Manager::refresh_devices([[maybe_unused]] bool add, [[maybe_unused]] bool remove)
{
// collect currently connected devices
RtMidiIn enumerator {};
std::map<std::size_t, std::string> port_map {};
for (std::size_t i = 0; i < enumerator.getPortCount(); ++i)
{
std::string name = enumerator.getPortName(i);
port_map[i] = name;
}
for (auto & [id, device] : m_connections)
{
for (auto const & [port, name] : port_map)
{
if (name.contains(device->device_name))
{
device->reconnect(port);
}
}
}
}
} // namespace midi_router
|