-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfigfileparser.cpp
116 lines (87 loc) · 2.48 KB
/
configfileparser.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
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
#include "configfileparser.h"
#include <iostream>
#include <fstream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/istreamwrapper.h"
using namespace rapidjson;
ConfigFileParser::ConfigFileParser(std::string name):
fileName(name)
{
}
bool ConfigFileParser::Init()
{
bool result = false;
std::ifstream ifs(fileName);
if(ifs.is_open())
{
Document document;
IStreamWrapper wp(ifs);
document.ParseStream(wp);
for(auto it=document.MemberBegin(); it<document.MemberEnd(); ++it)
{
std::cout << "Element name=" << it->name.GetString() << std::endl;
string node(it->name.GetString());
if(node == "Type")
{
params = factoryParams(IParams::getTypeParam(it->value.GetString()));
}
if((node == "Params") && (params))
{
result = params->fromJSON(it->value);
}
}
}
else
{
std::cout << "Error. Config file not exist" << std::endl;
}
return result;
}
bool ConfigFileParser::generateJSON(TypeParam type)
{
bool result = false;
TypeParams temp_params = factoryParams(type);
if(temp_params)
{
rapidjson::Document doc;
auto& allocator = doc.GetAllocator();
doc.SetObject();
rapidjson::Value val;
val.SetString(IParams::getStringType(type).c_str(), allocator);
doc.AddMember("Type", val, allocator);
temp_params->toJSON(doc);
rapidjson::StringBuffer buffer;
//rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
std::string filename("generate_");
filename += temp_params->getName();
filename += ".json";
std::ofstream out(filename);
if(!out)
{
std::cout << "Error open file " << filename << std::endl;
return result;
}
out << buffer.GetString();
out.close();
result = true;
}
return result;
}
TypeParams ConfigFileParser::factoryParams(TypeParam type)
{
TypeParams result = nullptr;
if(type == TypeParam::RS232)
{
result = std::make_shared<ParamsRS232>("/dev/ttyS0");
}
else
if(type == TypeParam::UDP)
{
result = std::make_shared<ParamsUDP>();
}
return result;
}