综合平台编程器项目的远程存储
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

777 linhas
34 KiB

  1. #include "domain/project_storage.h"
  2. #include "infrastructure/json_project_storage.h"
  3. #include "services/register_comment_service.h"
  4. #include "services/project_service.h"
  5. #include <QFile>
  6. #include <QJsonArray>
  7. #include <QJsonDocument>
  8. #include <QJsonObject>
  9. #include <QTemporaryDir>
  10. #include <exception>
  11. #include <iostream>
  12. #include <stdexcept>
  13. #include <string>
  14. #include <utility>
  15. namespace {
  16. void require(bool condition, const std::string &message)
  17. {
  18. if (!condition)
  19. {
  20. throw std::runtime_error(message);
  21. }
  22. }
  23. Project makeExampleProject()
  24. {
  25. // 构造覆盖 HMI 控件和梯形图串并联结构的完整 JSON 往返样本
  26. HmiControl start_button;
  27. start_button.id = "start-button";
  28. start_button.type = HmiControlType::Button;
  29. start_button.bounds = {10, 20, 120, 48};
  30. start_button.text = "Start";
  31. start_button.binding = RegisterAddress{RegisterArea::M, 0};
  32. start_button.buttonOperation = HmiButtonOperation::SetOn;
  33. start_button.properties.emplace("color", "green");
  34. HmiControl running_indicator;
  35. running_indicator.id = "running-indicator";
  36. running_indicator.type = HmiControlType::Indicator;
  37. running_indicator.bounds = {150, 20, 64, 64};
  38. running_indicator.text = "Running";
  39. running_indicator.binding = RegisterAddress{RegisterArea::M, 1};
  40. running_indicator.properties.emplace("activeColor", "#24a148");
  41. HmiControl temperature_display;
  42. temperature_display.id = "temperature-display";
  43. temperature_display.type = HmiControlType::NumericDisplay;
  44. temperature_display.bounds = {10, 90, 120, 40};
  45. temperature_display.text = "Temperature";
  46. temperature_display.binding = RegisterAddress{RegisterArea::D, 2};
  47. temperature_display.properties.emplace("format", "decimal");
  48. HmiControl target_input;
  49. target_input.id = "target-input";
  50. target_input.type = HmiControlType::NumericInput;
  51. target_input.bounds = {150, 90, 120, 40};
  52. target_input.text = "Target";
  53. target_input.binding = RegisterAddress{RegisterArea::D, 3};
  54. target_input.properties.emplace("minimum", "-100");
  55. HmiControl title_label;
  56. title_label.id = "title-label";
  57. title_label.type = HmiControlType::Label;
  58. title_label.bounds = {10, 145, 180, 32};
  59. title_label.text = "Production line";
  60. HmiControl settings_jump;
  61. settings_jump.id = "settings-jump";
  62. settings_jump.type = HmiControlType::PageJump;
  63. settings_jump.bounds = {210, 145, 120, 40};
  64. settings_jump.text = "Settings";
  65. settings_jump.pageJump = HmiPageJumpConfig{"settings-page"};
  66. HmiControl alarm_list;
  67. alarm_list.id = "alarm-list";
  68. alarm_list.type = HmiControlType::AlarmList;
  69. alarm_list.bounds = {10, 200, 360, 180};
  70. alarm_list.text = "Alarms";
  71. HmiControl progress_bar;
  72. progress_bar.id = "progress-bar";
  73. progress_bar.type = HmiControlType::ProgressBar;
  74. progress_bar.bounds = {400, 20, 240, 36};
  75. progress_bar.text = "Completion";
  76. progress_bar.binding = RegisterAddress{RegisterArea::D, 4};
  77. progress_bar.progressBar = HmiProgressBarConfig{-20, 80, true};
  78. HmiPage page;
  79. page.id = "main-page";
  80. page.name = "Main";
  81. page.controls.push_back(start_button);
  82. page.controls.push_back(running_indicator);
  83. page.controls.push_back(temperature_display);
  84. page.controls.push_back(target_input);
  85. page.controls.push_back(title_label);
  86. page.controls.push_back(settings_jump);
  87. page.controls.push_back(alarm_list);
  88. page.controls.push_back(progress_bar);
  89. HmiPage settings_page;
  90. settings_page.id = "settings-page";
  91. settings_page.name = "Settings";
  92. LogicNode contact;
  93. contact.id = "start-contact";
  94. contact.config = ContactNodeConfig{
  95. RegisterAddress{RegisterArea::M, 0},
  96. ContactMode::NormallyOpen};
  97. LogicNode compare;
  98. compare.id = "temperature-check";
  99. compare.config = CompareNodeConfig{
  100. RegisterAddress{RegisterArea::D, 2},
  101. ComparisonOperator::GreaterThanOrEqual,
  102. static_cast<std::int16_t>(100)};
  103. LogicNode hold_contact;
  104. hold_contact.id = "hold-contact";
  105. hold_contact.config = ContactNodeConfig{
  106. RegisterAddress{RegisterArea::M, 1},
  107. ContactMode::NormallyOpen};
  108. LogicNode coil;
  109. coil.id = "run-coil";
  110. coil.config = CoilNodeConfig{
  111. RegisterAddress{RegisterArea::M, 1},
  112. CoilMode::Set};
  113. ControlLogic logic;
  114. logic.id = "start-logic";
  115. logic.name = "Start logic";
  116. logic.enabled = false;
  117. LadderRung rung;
  118. rung.id = "rung-1";
  119. rung.name = "Network 1";
  120. rung.comment = "启动条件与温度检查";
  121. ConditionExpression parallel;
  122. parallel.id = "parallel-start";
  123. parallel.kind = ConditionExpressionKind::Parallel;
  124. parallel.children = {
  125. ConditionExpression::fromNode(contact),
  126. ConditionExpression::fromNode(hold_contact)};
  127. ConditionExpression series;
  128. series.id = "series-root";
  129. series.kind = ConditionExpressionKind::Series;
  130. series.children = {
  131. std::move(parallel),
  132. ConditionExpression::fromNode(compare)};
  133. rung.condition = std::move(series);
  134. rung.output = coil;
  135. logic.rungs.push_back(rung);
  136. LogicNode rising_edge;
  137. rising_edge.id = "rising-edge";
  138. rising_edge.config = EdgeContactNodeConfig{
  139. RegisterAddress{RegisterArea::M, 4}, EdgeMode::Rising};
  140. LogicNode ton_output;
  141. ton_output.id = "ton-output";
  142. ton_output.config = TonNodeConfig{TimerAddress{7}, 2500};
  143. LadderRung ton_rung;
  144. ton_rung.id = "ton-rung";
  145. ton_rung.name = "TON network";
  146. ton_rung.comment = "延时启动";
  147. ton_rung.condition = ConditionExpression::fromNode(rising_edge);
  148. ton_rung.output = ton_output;
  149. logic.rungs.push_back(ton_rung);
  150. LogicNode falling_edge;
  151. falling_edge.id = "falling-edge";
  152. falling_edge.config = EdgeContactNodeConfig{
  153. RegisterAddress{RegisterArea::M, 5}, EdgeMode::Falling};
  154. LogicNode timer_contact;
  155. timer_contact.id = "timer-contact";
  156. timer_contact.config = TimerContactNodeConfig{
  157. TimerAddress{7}, ContactMode::NormallyOpen};
  158. LogicNode timer_coil;
  159. timer_coil.id = "timer-coil";
  160. timer_coil.config = CoilNodeConfig{
  161. RegisterAddress{RegisterArea::M, 6}, CoilMode::Normal};
  162. LadderRung timer_rung;
  163. timer_rung.id = "timer-rung";
  164. timer_rung.name = "Timer feedback";
  165. timer_rung.comment = "定时器完成反馈";
  166. ConditionExpression timer_series;
  167. timer_series.id = "timer-series";
  168. timer_series.kind = ConditionExpressionKind::Series;
  169. timer_series.children = {
  170. ConditionExpression::fromNode(falling_edge),
  171. ConditionExpression::fromNode(timer_contact)};
  172. timer_rung.condition = std::move(timer_series);
  173. timer_rung.output = timer_coil;
  174. logic.rungs.push_back(timer_rung);
  175. LogicNode counter_input;
  176. counter_input.id = "counter-input";
  177. counter_input.config = ContactNodeConfig{
  178. RegisterAddress{RegisterArea::M, 7}, ContactMode::NormallyOpen};
  179. LogicNode counter_output;
  180. counter_output.id = "counter-output";
  181. counter_output.config = CounterNodeConfig{
  182. CounterAddress{3},
  183. CounterMode::Up,
  184. RegisterAddress{RegisterArea::D, 10},
  185. WordOperand{
  186. WordOperandKind::Register,
  187. RegisterAddress{RegisterArea::D, 11},
  188. 0},
  189. RegisterAddress{RegisterArea::M, 8}};
  190. LadderRung counter_rung;
  191. counter_rung.id = "counter-rung";
  192. counter_rung.name = "Counter network";
  193. counter_rung.comment = "计数器上升沿计数";
  194. counter_rung.condition = ConditionExpression::fromNode(counter_input);
  195. counter_rung.output = counter_output;
  196. logic.rungs.push_back(counter_rung);
  197. LogicNode counter_contact;
  198. counter_contact.id = "counter-contact";
  199. counter_contact.config = CounterContactNodeConfig{
  200. CounterAddress{3}, ContactMode::NormallyOpen};
  201. LogicNode counter_coil;
  202. counter_coil.id = "counter-coil";
  203. counter_coil.config = CoilNodeConfig{
  204. RegisterAddress{RegisterArea::M, 9}, CoilMode::Normal};
  205. LadderRung counter_feedback_rung;
  206. counter_feedback_rung.id = "counter-feedback-rung";
  207. counter_feedback_rung.name = "Counter feedback";
  208. counter_feedback_rung.condition = ConditionExpression::fromNode(counter_contact);
  209. counter_feedback_rung.output = counter_coil;
  210. logic.rungs.push_back(counter_feedback_rung);
  211. const auto addDataRung = [&logic](
  212. const std::string &rung_id,
  213. const std::string &input_id,
  214. int input_address,
  215. LogicNode output)
  216. {
  217. LogicNode input;
  218. input.id = input_id;
  219. input.config = ContactNodeConfig{
  220. RegisterAddress{RegisterArea::M, input_address},
  221. ContactMode::NormallyOpen};
  222. LadderRung data_rung;
  223. data_rung.id = rung_id;
  224. data_rung.name = rung_id;
  225. data_rung.condition = ConditionExpression::fromNode(input);
  226. data_rung.output = std::move(output);
  227. logic.rungs.push_back(std::move(data_rung));
  228. };
  229. addDataRung(
  230. "move-rung",
  231. "move-input",
  232. 20,
  233. LogicNode{
  234. "move-output",
  235. MoveNodeConfig{
  236. WordOperand{
  237. WordOperandKind::Constant,
  238. RegisterAddress{RegisterArea::D, 0},
  239. 25},
  240. RegisterAddress{RegisterArea::D, 20}},
  241. true});
  242. addDataRung(
  243. "add-rung",
  244. "add-input",
  245. 21,
  246. LogicNode{
  247. "add-output",
  248. ArithmeticNodeConfig{
  249. ArithmeticOperation::Add,
  250. WordOperand{
  251. WordOperandKind::Register,
  252. RegisterAddress{RegisterArea::D, 20},
  253. 0},
  254. WordOperand{
  255. WordOperandKind::Constant,
  256. RegisterAddress{RegisterArea::D, 0},
  257. 1},
  258. RegisterAddress{RegisterArea::D, 21}},
  259. true});
  260. addDataRung(
  261. "sub-rung",
  262. "sub-input",
  263. 22,
  264. LogicNode{
  265. "sub-output",
  266. ArithmeticNodeConfig{
  267. ArithmeticOperation::Subtract,
  268. WordOperand{
  269. WordOperandKind::Register,
  270. RegisterAddress{RegisterArea::D, 21},
  271. 0},
  272. WordOperand{
  273. WordOperandKind::Constant,
  274. RegisterAddress{RegisterArea::D, 0},
  275. 1},
  276. RegisterAddress{RegisterArea::D, 22}},
  277. true});
  278. Project project;
  279. project.metadata = {"example-project", "Example project", "1.0"};
  280. project.hmiPages.push_back(page);
  281. project.hmiPages.push_back(settings_page);
  282. project.initialHmiPageId = page.id;
  283. project.alarmDefinitions.push_back(
  284. {"alarm-emergency",
  285. RegisterAddress{RegisterArea::M, 10},
  286. AlarmCondition::MOn,
  287. 0,
  288. "Emergency stop"});
  289. project.alarmDefinitions.push_back(
  290. {"alarm-temperature",
  291. RegisterAddress{RegisterArea::D, 2},
  292. AlarmCondition::DHigh,
  293. 80,
  294. "Temperature high"});
  295. project.registerComments = {
  296. {RegisterAddress{RegisterArea::M, 0}, "启动按钮"},
  297. {RegisterAddress{RegisterArea::D, 2}, "当前温度"}};
  298. project.controlLogics.push_back(logic);
  299. ControlLogic draft_logic;
  300. draft_logic.id = "draft-logic";
  301. draft_logic.name = "Draft logic";
  302. draft_logic.enabled = false;
  303. draft_logic.rungs.push_back(
  304. {"rung-1", "Draft network", {}, std::nullopt, std::nullopt});
  305. project.controlLogics.push_back(draft_logic);
  306. return project;
  307. }
  308. void writeText(const QString &path, const QByteArray &content)
  309. {
  310. // 直接写入故障样本文件,以验证加载失败时的保护行为
  311. QFile file(path);
  312. require(file.open(QIODevice::WriteOnly), "test file must be writable");
  313. require(file.write(content) == content.size(), "test file must be written completely");
  314. }
  315. QByteArray readBytes(const QString &path)
  316. {
  317. QFile file(path);
  318. require(file.open(QIODevice::ReadOnly), "saved project must be readable");
  319. return file.readAll();
  320. }
  321. void testEmptyProjectRoundTrip()
  322. {
  323. // 空工程是合法工程,保存再加载后不应凭空产生页面或逻辑
  324. QTemporaryDir directory;
  325. require(directory.isValid(), "temporary directory must be valid");
  326. JsonProjectStorage storage;
  327. ProjectService service(storage);
  328. require(service.createNewProject("Empty project").succeeded,
  329. "empty project creation must succeed");
  330. const QString path = directory.filePath("empty.json");
  331. require(service.saveAs(path.toStdString()).succeeded,
  332. "empty project save must succeed");
  333. require(!service.isModified(), "saved project must not be marked modified");
  334. require(service.load(path.toStdString()).succeeded,
  335. "empty project load must succeed");
  336. require(service.project().metadata.name == "Empty project",
  337. "empty project name must survive round trip");
  338. require(service.project().hmiPages.empty(), "empty project must have no HMI pages");
  339. require(service.project().controlLogics.empty(),
  340. "empty project must have no control logics");
  341. require(service.project().alarmDefinitions.empty(),
  342. "empty project must have no alarm definitions");
  343. }
  344. void testExampleProjectRoundTrip()
  345. {
  346. // 验证各层嵌套字段往返后保持不变且序列化结果稳定
  347. QTemporaryDir directory;
  348. require(directory.isValid(), "temporary directory must be valid");
  349. JsonProjectStorage storage;
  350. ProjectService service(storage);
  351. service.editProject() = makeExampleProject();
  352. const QString first_path = directory.filePath("example.json");
  353. const QString second_path = directory.filePath("example-copy.json");
  354. const QString invalid_operation_path = directory.filePath("invalid-operation.json");
  355. const QString missing_initial_path = directory.filePath("missing-initial.json");
  356. const QString missing_target_path = directory.filePath("missing-target.json");
  357. const QString missing_progress_range_path = directory.filePath(
  358. "missing-progress-range.json");
  359. const QString missing_alarms_path = directory.filePath("missing-alarms.json");
  360. const QString missing_register_comments_path = directory.filePath(
  361. "missing-register-comments.json");
  362. const QString missing_rung_comment_path = directory.filePath(
  363. "missing-rung-comment.json");
  364. require(service.saveAs(first_path.toStdString()).succeeded,
  365. "example project save must succeed");
  366. const QByteArray saved_json = readBytes(first_path);
  367. require(saved_json.contains("\"rungs\"")
  368. && saved_json.contains("\"condition\"")
  369. && saved_json.contains("\"children\"")
  370. && saved_json.contains("\"output\""),
  371. "saved project must use structured ladder expressions");
  372. require(!saved_json.contains("\"dataPoints\""),
  373. "saved project must not contain the removed data point model");
  374. require(saved_json.contains("\"formatVersion\": \"1.0\"")
  375. && saved_json.contains("\"buttonOperation\": \"setOn\"")
  376. && saved_json.contains("\"initialHmiPageId\": \"main-page\"")
  377. && saved_json.contains("\"targetPageId\": \"settings-page\"")
  378. && saved_json.contains("\"alarmDefinitions\"")
  379. && saved_json.contains("\"registerComments\"")
  380. && saved_json.contains("\"text\": \"启动按钮\"")
  381. && saved_json.contains("\"type\": \"edgeContact\"")
  382. && saved_json.contains("\"type\": \"timerContact\"")
  383. && saved_json.contains("\"type\": \"ton\"")
  384. && saved_json.contains("\"type\": \"counterContact\"")
  385. && saved_json.contains("\"type\": \"counter\"")
  386. && saved_json.contains("\"type\": \"move\"")
  387. && saved_json.contains("\"type\": \"arithmetic\"")
  388. && saved_json.contains("\"operation\": \"add\"")
  389. && saved_json.contains("\"operation\": \"subtract\"")
  390. && saved_json.contains("\"comment\": \"启动条件与温度检查\"")
  391. && saved_json.contains("\"type\": \"alarmList\"")
  392. && saved_json.contains("\"type\": \"progressBar\"")
  393. && saved_json.contains("\"minimumValue\": -20")
  394. && saved_json.contains("\"maximumValue\": 80")
  395. && saved_json.contains("\"showValue\": true"),
  396. "version 1.0 projects must persist pages and alarm definitions");
  397. require(!saved_json.contains("\"stages\"")
  398. && !saved_json.contains("\"branches\""),
  399. "current project format must not contain the removed stage model");
  400. require(!saved_json.contains("\"position\"")
  401. && !saved_json.contains("\"connections\""),
  402. "saved ladder logic must not contain free-graph fields");
  403. require(service.load(first_path.toStdString()).succeeded,
  404. "example project load must succeed");
  405. const Project &project = service.project();
  406. require(project.metadata.id == "example-project", "project id must survive round trip");
  407. require(project.hmiPages.size() == 2, "HMI page count must survive round trip");
  408. require(project.initialHmiPageId == "main-page",
  409. "the initial HMI page id must survive round trip");
  410. require(project.hmiPages.front().controls.size() == 8,
  411. "register, navigation, AlarmList and ProgressBar controls must survive round trip");
  412. require(project.hmiPages.front().controls.front().binding->area()
  413. == RegisterArea::M,
  414. "HMI M binding must survive round trip");
  415. require(project.hmiPages.front().controls.front().buttonOperation
  416. == HmiButtonOperation::SetOn,
  417. "HMI button operation must survive round trip");
  418. require(project.hmiPages.front().controls.front().properties.at("color") == "green",
  419. "HMI properties must survive round trip");
  420. require(project.hmiPages.front().controls.at(1).type == HmiControlType::Indicator,
  421. "indicator control type must survive round trip");
  422. require(project.hmiPages.front().controls.at(2).binding->area() == RegisterArea::D,
  423. "numeric display D binding must survive round trip");
  424. require(project.hmiPages.front().controls.at(3).bounds.x == 150,
  425. "numeric input bounds must survive round trip");
  426. require(project.hmiPages.front().controls.at(4).type == HmiControlType::Label
  427. && project.hmiPages.front().controls.at(5).pageJump->targetPageId
  428. == "settings-page",
  429. "Label and PageJump typed data must survive round trip");
  430. require(project.hmiPages.front().controls.at(6).type
  431. == HmiControlType::AlarmList,
  432. "AlarmList control type must survive round trip");
  433. require(project.hmiPages.front().controls.at(7).type
  434. == HmiControlType::ProgressBar
  435. && project.hmiPages.front().controls.at(7).progressBar.has_value()
  436. && project.hmiPages.front().controls.at(7).progressBar->minimumValue == -20
  437. && project.hmiPages.front().controls.at(7).progressBar->maximumValue == 80
  438. && project.hmiPages.front().controls.at(7).progressBar->showValue,
  439. "ProgressBar configuration must survive round trip");
  440. require(project.alarmDefinitions.size() == 2
  441. && project.alarmDefinitions.front().condition
  442. == AlarmCondition::MOn
  443. && project.alarmDefinitions.at(1).threshold == 80,
  444. "M and D alarm definitions must survive round trip");
  445. require(project.registerComments.size() == 2
  446. && project.registerComments.front().address.area() == RegisterArea::M
  447. && project.registerComments.front().text == "启动按钮"
  448. && project.registerComments.at(1).address.area() == RegisterArea::D,
  449. "M/D register comments must survive round trip");
  450. require(project.controlLogics.size() == 2,
  451. "control logic count must survive round trip");
  452. require(!project.controlLogics.front().enabled,
  453. "control logic enabled state must survive round trip");
  454. const LadderRung &rung = project.controlLogics.front().rungs.front();
  455. require(rung.comment == "启动条件与温度检查",
  456. "rung comments must survive round trip");
  457. require(rung.condition.has_value()
  458. && rung.condition->kind == ConditionExpressionKind::Series,
  459. "series root expression must survive round trip");
  460. require(rung.condition->children.front().kind
  461. == ConditionExpressionKind::Parallel
  462. && rung.condition->children.front().children.size() == 2U,
  463. "parallel expression branches must survive round trip");
  464. require(rung.output.has_value(),
  465. "ladder output must survive round trip");
  466. const LadderRung &ton_rung = project.controlLogics.front().rungs.at(1);
  467. require(ton_rung.output.has_value()
  468. && std::holds_alternative<TonNodeConfig>(ton_rung.output->config)
  469. && std::get<TonNodeConfig>(ton_rung.output->config).address
  470. == TimerAddress{7}
  471. && std::get<TonNodeConfig>(ton_rung.output->config).presetMs == 2500,
  472. "TON timer address and preset must survive round trip");
  473. require(std::holds_alternative<EdgeContactNodeConfig>(
  474. ton_rung.condition->node->config)
  475. && std::get<EdgeContactNodeConfig>(ton_rung.condition->node->config).mode
  476. == EdgeMode::Rising,
  477. "rising edge configuration must survive round trip");
  478. const LadderRung &timer_rung = project.controlLogics.front().rungs.at(2);
  479. require(timer_rung.comment == "定时器完成反馈"
  480. && std::holds_alternative<TimerContactNodeConfig>(
  481. timer_rung.condition->children.at(1).node->config)
  482. && std::get<TimerContactNodeConfig>(
  483. timer_rung.condition->children.at(1).node->config).address
  484. == TimerAddress{7}
  485. && std::holds_alternative<EdgeContactNodeConfig>(
  486. timer_rung.condition->children.front().node->config)
  487. && std::get<EdgeContactNodeConfig>(
  488. timer_rung.condition->children.front().node->config).mode
  489. == EdgeMode::Falling,
  490. "falling edge and T contact configurations must survive round trip");
  491. const LadderRung &counter_rung = project.controlLogics.front().rungs.at(3);
  492. const auto &counter = std::get<CounterNodeConfig>(counter_rung.output->config);
  493. require(counter.address == CounterAddress{3}
  494. && counter.currentValueAddress == RegisterAddress{RegisterArea::D, 10}
  495. && counter.preset.kind == WordOperandKind::Register
  496. && counter.preset.address == RegisterAddress{RegisterArea::D, 11}
  497. && counter.resetAddress == RegisterAddress{RegisterArea::M, 8},
  498. "counter resource and external M/D addresses must survive round trip");
  499. const LadderRung &counter_feedback = project.controlLogics.front().rungs.at(4);
  500. require(std::holds_alternative<CounterContactNodeConfig>(
  501. counter_feedback.condition->node->config)
  502. && std::get<CounterContactNodeConfig>(
  503. counter_feedback.condition->node->config).address
  504. == CounterAddress{3},
  505. "counter contacts must survive round trip");
  506. require(std::get<MoveNodeConfig>(
  507. project.controlLogics.front().rungs.at(5).output->config)
  508. .source.constant == 25,
  509. "MOVE operands must survive round trip");
  510. require(std::get<ArithmeticNodeConfig>(
  511. project.controlLogics.front().rungs.at(6).output->config)
  512. .operation == ArithmeticOperation::Add
  513. && std::get<ArithmeticNodeConfig>(
  514. project.controlLogics.front().rungs.at(7).output->config)
  515. .operation == ArithmeticOperation::Subtract,
  516. "ADD and SUB operations must survive round trip");
  517. const auto &compare = std::get<CompareNodeConfig>(
  518. rung.condition->children.at(1).node->config);
  519. require(compare.address.index() == 2 && compare.value == 100,
  520. "comparison configuration must survive round trip");
  521. require(service.saveAs(second_path.toStdString()).succeeded,
  522. "save as must succeed after load");
  523. require(readBytes(first_path) == readBytes(second_path),
  524. "save and save as must produce stable JSON");
  525. QByteArray invalid_operation = saved_json;
  526. invalid_operation.replace(
  527. "\"buttonOperation\": \"setOn\"",
  528. "\"buttonOperation\": \"unsupported\"");
  529. writeText(invalid_operation_path, invalid_operation);
  530. require(!service.load(invalid_operation_path.toStdString()).succeeded,
  531. "unsupported HMI button operations must be rejected");
  532. QJsonObject missing_initial = QJsonDocument::fromJson(saved_json).object();
  533. missing_initial.remove(QStringLiteral("initialHmiPageId"));
  534. writeText(
  535. missing_initial_path,
  536. QJsonDocument(missing_initial).toJson(QJsonDocument::Compact));
  537. ProjectOperationResult missing_result = service.load(
  538. missing_initial_path.toStdString());
  539. require(!missing_result.succeeded
  540. && missing_result.storageError == ProjectStorageError::MissingField,
  541. "the 1.0 schema must require initialHmiPageId without migration defaults");
  542. QJsonObject missing_alarms = QJsonDocument::fromJson(saved_json).object();
  543. missing_alarms.remove(QStringLiteral("alarmDefinitions"));
  544. writeText(
  545. missing_alarms_path,
  546. QJsonDocument(missing_alarms).toJson(QJsonDocument::Compact));
  547. missing_result = service.load(missing_alarms_path.toStdString());
  548. require(!missing_result.succeeded
  549. && missing_result.storageError == ProjectStorageError::MissingField,
  550. "the 1.0 schema must require alarmDefinitions without migration defaults");
  551. QJsonObject missing_register_comments = QJsonDocument::fromJson(saved_json).object();
  552. missing_register_comments.remove(QStringLiteral("registerComments"));
  553. writeText(
  554. missing_register_comments_path,
  555. QJsonDocument(missing_register_comments).toJson(QJsonDocument::Compact));
  556. missing_result = service.load(missing_register_comments_path.toStdString());
  557. require(!missing_result.succeeded
  558. && missing_result.storageError == ProjectStorageError::MissingField,
  559. "the 1.0 schema must require registerComments without migration defaults");
  560. QJsonObject missing_rung_comment = QJsonDocument::fromJson(saved_json).object();
  561. QJsonArray missing_comment_logics = missing_rung_comment.value(
  562. QStringLiteral("controlLogics")).toArray();
  563. QJsonObject first_logic = missing_comment_logics.at(0).toObject();
  564. QJsonArray first_rungs = first_logic.value(QStringLiteral("rungs")).toArray();
  565. QJsonObject first_rung = first_rungs.at(0).toObject();
  566. first_rung.remove(QStringLiteral("comment"));
  567. first_rungs.replace(0, first_rung);
  568. first_logic.insert(QStringLiteral("rungs"), first_rungs);
  569. missing_comment_logics.replace(0, first_logic);
  570. missing_rung_comment.insert(QStringLiteral("controlLogics"), missing_comment_logics);
  571. writeText(
  572. missing_rung_comment_path,
  573. QJsonDocument(missing_rung_comment).toJson(QJsonDocument::Compact));
  574. missing_result = service.load(missing_rung_comment_path.toStdString());
  575. require(!missing_result.succeeded
  576. && missing_result.storageError == ProjectStorageError::MissingField,
  577. "the 1.0 schema must require rung comments without migration defaults");
  578. QJsonObject missing_target = QJsonDocument::fromJson(saved_json).object();
  579. QJsonArray pages = missing_target.value(QStringLiteral("hmiPages")).toArray();
  580. QJsonObject main_page = pages.at(0).toObject();
  581. QJsonArray controls = main_page.value(QStringLiteral("controls")).toArray();
  582. QJsonObject jump = controls.at(5).toObject();
  583. jump.remove(QStringLiteral("targetPageId"));
  584. controls.replace(5, jump);
  585. main_page.insert(QStringLiteral("controls"), controls);
  586. pages.replace(0, main_page);
  587. missing_target.insert(QStringLiteral("hmiPages"), pages);
  588. writeText(
  589. missing_target_path,
  590. QJsonDocument(missing_target).toJson(QJsonDocument::Compact));
  591. missing_result = service.load(missing_target_path.toStdString());
  592. require(!missing_result.succeeded
  593. && missing_result.storageError == ProjectStorageError::MissingField,
  594. "the 1.0 schema must require PageJump targetPageId");
  595. QJsonObject missing_progress_range = QJsonDocument::fromJson(saved_json).object();
  596. pages = missing_progress_range.value(QStringLiteral("hmiPages")).toArray();
  597. main_page = pages.at(0).toObject();
  598. controls = main_page.value(QStringLiteral("controls")).toArray();
  599. QJsonObject progress = controls.at(7).toObject();
  600. progress.remove(QStringLiteral("maximumValue"));
  601. controls.replace(7, progress);
  602. main_page.insert(QStringLiteral("controls"), controls);
  603. pages.replace(0, main_page);
  604. missing_progress_range.insert(QStringLiteral("hmiPages"), pages);
  605. writeText(
  606. missing_progress_range_path,
  607. QJsonDocument(missing_progress_range).toJson(QJsonDocument::Compact));
  608. missing_result = service.load(missing_progress_range_path.toStdString());
  609. require(!missing_result.succeeded
  610. && missing_result.storageError == ProjectStorageError::MissingField,
  611. "the 1.0 schema must require the ProgressBar value range");
  612. }
  613. void testInvalidFiles()
  614. {
  615. // 非法文件必须被拒绝,并且不得覆盖服务中当前工程
  616. QTemporaryDir directory;
  617. require(directory.isValid(), "temporary directory must be valid");
  618. JsonProjectStorage storage;
  619. ProjectService service(storage);
  620. service.editProject().metadata.name = "Current project";
  621. const QString invalid_json = directory.filePath("invalid-json.json");
  622. const QString missing_field = directory.filePath("missing-field.json");
  623. const QString unsupported_version = directory.filePath("unsupported-version.json");
  624. writeText(invalid_json, "{");
  625. auto result = service.load(invalid_json.toStdString());
  626. require(!result.succeeded
  627. && result.storageError == ProjectStorageError::InvalidJson,
  628. "invalid JSON must be rejected");
  629. require(service.project().metadata.name == "Current project",
  630. "invalid load must keep current project");
  631. writeText(missing_field, R"({"formatVersion":"1.0"})");
  632. result = service.load(missing_field.toStdString());
  633. require(!result.succeeded
  634. && result.storageError == ProjectStorageError::MissingField,
  635. "missing fields must be rejected");
  636. writeText(unsupported_version, R"({"formatVersion":"2.0"})");
  637. result = service.load(unsupported_version.toStdString());
  638. require(!result.succeeded
  639. && result.storageError == ProjectStorageError::UnsupportedVersion,
  640. "unsupported versions must be rejected");
  641. }
  642. void testServiceStateAndSaveErrors()
  643. {
  644. // 保存路径和修改标记只在成功持久化后更新
  645. QTemporaryDir directory;
  646. require(directory.isValid(), "temporary directory must be valid");
  647. JsonProjectStorage storage;
  648. ProjectService service(storage);
  649. require(service.save().error == ProjectServiceError::FilePathRequired,
  650. "save without a current path must be rejected");
  651. require(service.createNewProject(" ").error
  652. == ProjectServiceError::InvalidProjectName,
  653. "blank project names must be rejected");
  654. const QString path = directory.filePath("state.json");
  655. service.editProject().metadata.name = "State project";
  656. require(service.saveAs(path.toStdString()).succeeded,
  657. "state project save must succeed");
  658. service.editProject().metadata.name = "Changed project";
  659. require(service.isModified(), "editing the project must mark it modified");
  660. require(service.save().succeeded, "save must use the current file path");
  661. require(!service.isModified(), "successful save must clear modified state");
  662. const QString failed_path = directory.filePath("missing/subdir/state.json");
  663. require(!service.saveAs(failed_path.toStdString()).succeeded,
  664. "save to an unavailable path must fail");
  665. require(service.currentFilePath() == path.toStdString(),
  666. "failed save as must keep the previous current path");
  667. }
  668. void testRegisterCommentService()
  669. {
  670. JsonProjectStorage storage;
  671. ProjectService project_service(storage);
  672. RegisterCommentService service(project_service);
  673. require(service.setComment(
  674. RegisterAddress{RegisterArea::D, 3}, " 目标温度 ").succeeded,
  675. "register comment service must create a trimmed D comment");
  676. require(service.setComment(
  677. RegisterAddress{RegisterArea::M, 2}, "启动信号").succeeded,
  678. "register comment service must create an M comment");
  679. require(service.comments().size() == 2U
  680. && service.comments().front().address.area() == RegisterArea::M
  681. && service.comments().front().address.index() == 2
  682. && service.comments().back().text == "目标温度",
  683. "register comments must be sorted by area and address");
  684. require(service.setComment(
  685. RegisterAddress{RegisterArea::M, 2}, "新的启动信号").succeeded
  686. && service.comments().size() == 2U
  687. && service.findComment(RegisterAddress{RegisterArea::M, 2})->text
  688. == "新的启动信号",
  689. "setting an existing address must update instead of duplicating it");
  690. require(!service.setComment(RegisterAddress{RegisterArea::M, 4}, " \t").succeeded,
  691. "blank register comments must be rejected by the service");
  692. require(service.removeComment(RegisterAddress{RegisterArea::M, 2}).succeeded
  693. && service.findComment(RegisterAddress{RegisterArea::M, 2}) == nullptr,
  694. "register comments must be removable");
  695. require(!service.removeComment(RegisterAddress{RegisterArea::M, 2}).succeeded,
  696. "removing a missing register comment must fail explicitly");
  697. }
  698. } // namespace
  699. int main()
  700. {
  701. try
  702. {
  703. // 工程服务和 JSON 存储在同一测试进程中验证完整闭环
  704. testEmptyProjectRoundTrip();
  705. testExampleProjectRoundTrip();
  706. testRegisterCommentService();
  707. testInvalidFiles();
  708. testServiceStateAndSaveErrors();
  709. }
  710. catch (const std::exception &error)
  711. {
  712. std::cerr << "project management tests failed: " << error.what() << '\n';
  713. return 1;
  714. }
  715. std::cout << "project management tests passed\n";
  716. return 0;
  717. }