forked from Serial-Studio/Serial-Studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerator.cpp
More file actions
367 lines (319 loc) · 11.2 KB
/
Generator.cpp
File metadata and controls
367 lines (319 loc) · 11.2 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
* Copyright (c) 2020-2022 Alex Spataru <https://github.com/alex-spataru>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "Generator.h"
#include <QFileInfo>
#include <QFileDialog>
#include <QRegularExpression>
#include <Project/Model.h>
#include <Project/CodeEditor.h>
#include <CSV/Player.h>
#include <IO/Manager.h>
#include <MQTT/Client.h>
#include <Misc/Utilities.h>
/**
* Initializes the JSON Parser class and connects appropiate SIGNALS/SLOTS
*/
JSON::Generator::Generator()
: m_opMode(kAutomatic)
{
// clang-format off
connect(&CSV::Player::instance(), &CSV::Player::openChanged,
this, &JSON::Generator::reset);
connect(&IO::Manager::instance(), &IO::Manager::driverChanged,
this, &JSON::Generator::reset);
connect(&IO::Manager::instance(), &IO::Manager::frameReceived,
this, &JSON::Generator::readData);
// clang-format on
readSettings();
}
/**
* Returns the only instance of the class
*/
JSON::Generator &JSON::Generator::instance()
{
static Generator singleton;
return singleton;
}
/**
* Returns the JSON map data from the loaded file as a string
*/
QString JSON::Generator::jsonMapData() const
{
return m_jsonMapData;
}
/**
* Returns the file name (e.g. "JsonMap.json") of the loaded JSON map file
*/
QString JSON::Generator::jsonMapFilename() const
{
if (m_jsonMap.isOpen())
{
auto fileInfo = QFileInfo(m_jsonMap.fileName());
return fileInfo.fileName();
}
return "";
}
/**
* Returns the file path of the loaded JSON map file
*/
QString JSON::Generator::jsonMapFilepath() const
{
if (m_jsonMap.isOpen())
{
auto fileInfo = QFileInfo(m_jsonMap.fileName());
return fileInfo.filePath();
}
return "";
}
/**
* Returns the operation mode
*/
JSON::Generator::OperationMode JSON::Generator::operationMode() const
{
return m_opMode;
}
/**
* Creates a file dialog & lets the user select the JSON file map
*/
void JSON::Generator::loadJsonMap()
{
// clang-format off
auto file = QFileDialog::getOpenFileName(Q_NULLPTR,
tr("Select JSON map file"),
Project::Model::instance().jsonProjectsPath(),
tr("JSON files") + " (*.json)");
// clang-format on
if (!file.isEmpty())
loadJsonMap(file);
}
/**
* Opens, validates & loads into memory the JSON file in the given @a path.
*/
void JSON::Generator::loadJsonMap(const QString &path)
{
// Validate path
if (path.isEmpty())
return;
// Close previous file (if open)
if (m_jsonMap.isOpen())
{
m_jsonMap.close();
m_jsonMapData = "";
Q_EMIT jsonFileMapChanged();
}
// Try to open the file (read only mode)
m_jsonMap.setFileName(path);
if (m_jsonMap.open(QFile::ReadOnly))
{
// Read data & validate JSON from file
QJsonParseError error;
auto data = m_jsonMap.readAll();
auto document = QJsonDocument::fromJson(data, &error);
if (error.error != QJsonParseError::NoError)
{
m_jsonMap.close();
writeSettings("");
Misc::Utilities::showMessageBox(tr("JSON parse error"), error.errorString());
}
// JSON contains no errors, load compacted JSON document & save settings
else
{
// Save settings
writeSettings(path);
// Load compacted JSON document
document.object().remove("frameParser");
m_jsonMapData = QString::fromUtf8(document.toJson(QJsonDocument::Compact));
}
// Get rid of warnings
Q_UNUSED(document);
}
// Open error
else
{
m_jsonMapData = "";
writeSettings("");
Misc::Utilities::showMessageBox(tr("Cannot read JSON file"),
tr("Please check file permissions & location"));
m_jsonMap.close();
}
// Update UI
Q_EMIT jsonFileMapChanged();
}
/**
* Changes the operation mode of the JSON parser. There are two possible op.
* modes:
*
* @c kManual serial data only contains the comma-separated values, and we need
* to use a JSON map file (given by the user) to know what each value
* means. This method is recommended when we need to transfer &
* display a large amount of information from the microcontroller
* unit to the computer.
*
* @c kAutomatic serial data contains the JSON data frame, good for simple
* applications or for prototyping.
*/
void JSON::Generator::setOperationMode(const JSON::Generator::OperationMode &mode)
{
m_opMode = mode;
Q_EMIT operationModeChanged();
}
/**
* Loads the last saved JSON map file (if any)
*/
void JSON::Generator::readSettings()
{
auto path = m_settings.value("json_map_location", "").toString();
if (!path.isEmpty())
loadJsonMap(path);
}
/**
* Saves the location of the last valid JSON map file that was opened (if any)
*/
void JSON::Generator::writeSettings(const QString &path)
{
m_settings.setValue("json_map_location", path);
}
/**
* Resets all the statistics related to the current device and the JSON map file
*/
void JSON::Generator::reset()
{
m_json = QJsonObject();
m_latestValidValues.clear();
Q_EMIT jsonChanged(m_json);
}
/**
* Tries to parse the given data as a JSON document according to the selected
* operation mode.
*
* Possible operation modes:
* - Auto: serial data contains the JSON data frame
* - Manual: serial data only contains the comma-separated values, and we need
* to use a JSON map file (given by the user) to know what each value
* means
*
* If JSON parsing is successfull, then the class shall notify the rest of the
* application in order to process packet data.
*/
void JSON::Generator::readData(const QByteArray &data)
{
// Data empty, abort
if (data.isEmpty())
return;
// Serial device sends JSON (auto mode)
if (operationMode() == JSON::Generator::kAutomatic)
m_json = QJsonDocument::fromJson(data, &m_error).object();
// We need to use a map file, check if its loaded & replace values into map
else
{
// Empty JSON map data
if (jsonMapData().isEmpty())
return;
// Get fields from frame parser function
auto fields = Project::CodeEditor::instance().parse(
QString::fromUtf8(data), IO::Manager::instance().separatorSequence());
// Separate incoming data & add it to the JSON map
auto json = jsonMapData().toStdString();
for (int i = 0; i < fields.count(); ++i)
{
std::string id = "%" + std::to_string(i + 1);
size_t pos = json.find(id);
if (pos != std::string::npos && pos < json.length())
json.replace(pos, id.length(), fields.at(i).toStdString());
}
// Update latest JSON values list
if (fields.count() > m_latestValidValues.count())
{
m_latestValidValues.clear();
for (int i = 0; i < fields.count(); ++i)
m_latestValidValues.append("");
}
// Create JSON document
auto jsonData = QString::fromStdString(json).toUtf8();
m_json = QJsonDocument::fromJson(jsonData, &m_error).object();
}
// No parse error, evaluate any JS code
if (m_error.error == QJsonParseError::NoError)
{
// Initialize dataset counter
int datasetIndex = -1;
// Evaluate JavaScript code
bool evaluated = false;
auto groups = m_json.value("groups").toArray();
for (int i = 0; i < groups.count(); ++i)
{
// Get group & list of datasets
auto group = groups.at(i).toObject();
auto datasets = group.value("datasets").toArray();
// Evaluate value for each dataset
for (int j = 0; j < datasets.count(); ++j)
{
// Increment dataset index
++datasetIndex;
// Get dataset & value string
auto dataset = datasets.at(j).toObject();
auto value = dataset.value("value").toString();
//
// Update latest valid values array (or replace currently
// invalid value with the last known valid value)
//
if (datasetIndex < m_latestValidValues.count())
{
// Register latest value to list of valid values
if (!value.isEmpty() && !value.contains("%"))
m_latestValidValues.replace(datasetIndex, value);
// Invalid value, get the last known valid value
else
{
evaluated = true;
value = m_latestValidValues.at(datasetIndex);
dataset.remove("value");
dataset.insert("value", value);
}
}
}
// Replace evaluated datasets in group
if (evaluated)
{
//
// Reset eval. flag so that we only replace JSON data
// when required.
//
evaluated = false;
// Update datasets in group
group.remove("datasets");
group.insert("datasets", datasets);
// Update group in groups array
groups.removeAt(i);
groups.insert(i, group);
// Update groups array in JSON frame
m_json.remove("groups");
m_json.insert("groups", groups);
}
}
// Update UI
Q_EMIT jsonChanged(m_json);
}
}
#ifdef SERIAL_STUDIO_INCLUDE_MOC
# include "moc_Generator.cpp"
#endif