-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCommandParser.cpp
68 lines (59 loc) · 1.48 KB
/
CommandParser.cpp
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
#include "stdafx.h"
#include "json.hpp"
#include "CommandParser.h"
#include <string>
#include <algorithm>
namespace Commands
{
std::map< std::string, Commands::Type> lookUp
{
{ "Speed rise", Commands::Type::speedRise },
{ "Speed reduction", Commands::Type::speedDown },
{ "fuel drop", Commands::Type::fuelState },
};
Type CommandParser::type(const nlohmann::json& node)
{
auto eventInString = node["Event"];
return lookUp[eventInString];
}
int CommandParser::value(const nlohmann::json& node)
{
std::string valuInString = node["value"];
return std::atoi(valuInString.c_str());
}
int CommandParser::timeToProceed(const nlohmann::json& node)
{
if (node.find("timeToProceed") != node.end())
{
std::string timeInString = node["timeToProceed"];
return timeInString == "" ? 0 : std::atoi(timeInString.c_str());
}
return 0;
}
Command CommandParser::fromJason(const nlohmann::json& node)
{
auto event = type(node);
auto val = value(node);
auto time = timeToProceed(node);
return { event, val, time };
}
std::vector<Command> CommandParser::fromJason(std::string jasonAsString)
{
try
{
std::vector<Command> commands;
nlohmann::json jsonCommands = nlohmann::json::parse(jasonAsString)["Commands"];
std::for_each(jsonCommands.begin(), jsonCommands.end(), [&](const nlohmann::json& node)
{
auto command = fromJason(node);
commands.push_back(command);
}
);
return commands;
}
catch (...)
{
return std::vector<Command>();
}
}
}