-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.cpp
More file actions
133 lines (111 loc) · 2.69 KB
/
config.cpp
File metadata and controls
133 lines (111 loc) · 2.69 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <cstddef>
#include <cstring>
#include <fstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <iostream>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "config.hpp"
namespace multicast
{
namespace
{
Tokens split(std::string_view str)
{
std::vector<std::string_view> tokens{};
std::size_t start = 0;
while (true)
{
size_t pos = str.find(' ', start);
if (pos == std::string_view::npos)
{
tokens.emplace_back(str.substr(start));
break;
}
tokens.emplace_back(str.substr(start, pos - start));
start = pos + 1;
}
return tokens;
}
int parse_port(std::string_view str)
{
const int port = std::stoi(str.data());
static const int maxPort = 65535;
if (port < 0 || port > maxPort)
{
throw std::out_of_range("invalid port number");
}
return port;
}
} // namespace
UdpEntry::UdpEntry(const Tokens& tokens)
{
if (tokens.size() != 3)
{
throw std::runtime_error("can't create UDP client");
}
std::memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
std::string ipAddressStr{tokens[1]};
ipAddressStr.push_back('\0');
if (inet_pton(AF_INET, ipAddressStr.c_str(), &address.sin_addr) <= 0)
{
throw std::runtime_error("invalid IP address");
}
address.sin_port = htons(parse_port(tokens[2]));
}
SerialEntry::SerialEntry(const Tokens& tokens)
{
if (tokens.size() != 2)
{
throw std::runtime_error("can't create serial client");
}
device = tokens[1];
device.push_back('\0');
}
Config::Config(const std::filesystem::path& path)
{
if (!std::filesystem::exists(path))
{
throw std::runtime_error("configuration file does not exists!");
}
std::ifstream ifs{path};
if (!ifs || !ifs.good())
{
throw std::runtime_error("failed to open configuration file");
}
std::string line{};
while (std::getline(ifs, line))
{
auto tokens = split(line);
if (tokens.size() < 1)
{
throw std::runtime_error("failed to read configuration");
}
if (tokens[0] == "udp")
{
udpEnties_.emplace_back(UdpEntry{tokens});
}
else if (tokens[0] == "serial")
{
serialEntries_.emplace_back(SerialEntry{tokens});
}
else
{
throw std::runtime_error("unknown client");
}
}
}
const Config::UdpEntries& Config::GetUdpEntries() const
{
return udpEnties_;
}
const Config::SerialEntries& Config::GetSerialEntries() const
{
return serialEntries_;
}
} // namespace multicast