-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrabapi.cpp
More file actions
126 lines (107 loc) · 2.91 KB
/
grabapi.cpp
File metadata and controls
126 lines (107 loc) · 2.91 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
#include "grabapi.h"
GrabApi::GrabApi(std::string url, int delay, bool rolling, int numPoints) {
this->url = url;
this->delay = delay;
this->size = 0;
this->rolling = rolling;
this->numPoints = numPoints;
}
void GrabApi::timerEvent(QTimerEvent *event) {
std::string res;
if (this->rolling) {
res = GrabApi::request(this->url + "/" + std::to_string(1 + (this->numPoints * -1)));
}
else {
res = GrabApi::request(this->url + "/" + std::to_string(this->size));
}
if (res != "") {
std::vector<std::vector<double>> list = this->parseList(res);
if (rolling) {
emit appendPoints(list);
}
else {
for (auto point : list) {
emit addPoint(point[0], point[1]);
}
}
}
}
void GrabApi::start() {
this->timerId = startTimer(delay);
}
void GrabApi::stop() {
killTimer(timerId);
timerId = 0;
}
void GrabApi::Delete() {
delete this;
}
size_t GrabApi::curlWriteCallback(void* contents, size_t size, size_t nmemb, std::string* s)
{
size_t newLength = size * nmemb;
try
{
s->append((char*)contents, newLength);
}
catch (std::bad_alloc& e)
{
//handle memory problem
return 0;
}
return newLength;
}
std::string GrabApi::request(std::string url) {
CURL* curl;
CURLcode code;
std::string res;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, GrabApi::curlWriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &res);
code = curl_easy_perform(curl);
/* Check for errors */
if (code != CURLE_OK) {
//qDebug() << "Error " << code;
curl_easy_cleanup(curl);
return "";
}
/* always cleanup */
curl_easy_cleanup(curl);
}
return res;
}
GrabApi::~GrabApi() {}
std::vector<std::vector<double>> GrabApi::parseList(std::string data) {
std::vector<std::vector<double>> out;
std::vector<double>* point = new std::vector<double>;
std::string currVal = "";
for (int i = 1; i < data.length()-1; i++) {
char c = data[i];
if (c == '[') {
delete point;
point = new std::vector<double>;
}
else if (c == ']' || c==',') {
if (currVal != "") {
try {
point->push_back(stod(currVal));
currVal = "";
}
catch (std::invalid_argument) {
return *(new std::vector<std::vector<double>>);
}
}
if (c == ']') {
if (point->size() > 0) {
out.push_back(*point);
}
}
}
else if (c != ',') {
currVal += c;
}
}
delete point;
return out;
}