综合平台编程器项目的远程存储
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

934 satır
38 KiB

  1. #include "domain/control_logic_model.h"
  2. #include "domain/hmi_control_registry.h"
  3. #include "domain/hmi_model.h"
  4. #include "domain/project_model.h"
  5. #include "domain/project_limits.h"
  6. #include "domain/register_address.h"
  7. #include "domain/register_repository.h"
  8. #include "domain/runtime_state.h"
  9. #include "support/test_support.h"
  10. #include <cstdint>
  11. #include <exception>
  12. #include <functional>
  13. #include <iostream>
  14. #include <set>
  15. #include <stdexcept>
  16. #include <string>
  17. namespace {
  18. using TestSupport::require;
  19. void testRegisterAddressBoundaries()
  20. {
  21. // 覆盖 M/D 地址允许范围及未知枚举值的拒绝路径
  22. require(RegisterAddress{RegisterArea::M, 0}.isValid(),
  23. "M0 must be valid");
  24. require(RegisterAddress{RegisterArea::D, 4000}.isValid(),
  25. "D4000 must be valid");
  26. require(!(RegisterAddress{RegisterArea::M, -1}.isValid()),
  27. "negative register index must be rejected");
  28. require(!(RegisterAddress{RegisterArea::D, 4001}.isValid()),
  29. "register index above 4000 must be rejected");
  30. require(!(RegisterAddress{static_cast<RegisterArea>(99), 0}.isValid()),
  31. "unknown register area must be rejected");
  32. }
  33. void testRegisterAddressParsing()
  34. {
  35. const RegisterAddressParseResult m0 = parseRegisterAddress(" m0 ");
  36. require(m0.succeeded && m0.address == RegisterAddress{RegisterArea::M, 0},
  37. "register parser must trim and normalize lowercase M addresses");
  38. const RegisterAddressParseResult d4000 = parseRegisterAddress("D4000");
  39. require(d4000.succeeded
  40. && d4000.address == RegisterAddress{RegisterArea::D, 4000},
  41. "register parser must accept the maximum D address");
  42. require(parseRegisterAddress("").error == RegisterAddressParseError::Empty,
  43. "register parser must distinguish empty input");
  44. require(parseRegisterAddress("X0").error
  45. == RegisterAddressParseError::UnsupportedArea,
  46. "register parser must reject unsupported areas");
  47. require(parseRegisterAddress("M1.0").error
  48. == RegisterAddressParseError::InvalidFormat,
  49. "register parser must reject non-decimal indices");
  50. require(parseRegisterAddress("D4001").error
  51. == RegisterAddressParseError::OutOfRange,
  52. "register parser must reject addresses above the project range");
  53. }
  54. void testRegisterRepositorySeparatesAreas()
  55. {
  56. // 验证离线仓库不会把 M 位和 D 字交叉解释
  57. VirtualRegisterRepository repository;
  58. const RegisterAddress m0{RegisterArea::M, 0};
  59. const RegisterAddress d0{RegisterArea::D, 0};
  60. require(repository.writeBit(m0, true).succeeded, "M bit write must succeed");
  61. require(repository.readBit(m0).value, "M bit read must return written value");
  62. require(repository.writeWord(d0, static_cast<std::int16_t>(-123)).succeeded,
  63. "D word write must succeed");
  64. require(repository.readWord(d0).value == -123, "D word read must return written value");
  65. require(repository.readBit(d0).error == RegisterError::AreaMismatch,
  66. "D address must not be read as a bit");
  67. require(repository.readWord(m0).error == RegisterError::AreaMismatch,
  68. "M address must not be read as a word");
  69. }
  70. void testHmiControlRegistryCompleteness()
  71. {
  72. std::set<const HmiControlDescriptor *> descriptors;
  73. std::set<std::string> storage_names;
  74. std::set<std::string> id_prefixes;
  75. const std::size_t control_type_count =
  76. static_cast<std::size_t>(HmiControlType::Count);
  77. for (std::size_t index = 0; index < control_type_count; ++index)
  78. {
  79. const HmiControlType type = static_cast<HmiControlType>(index);
  80. const HmiControlDescriptor *descriptor =
  81. findHmiControlDescriptor(type);
  82. require(descriptor != nullptr,
  83. "every HMI control type must have one descriptor");
  84. require(descriptor->type == type,
  85. "HMI type lookup must return the requested descriptor");
  86. require(descriptors.emplace(descriptor).second,
  87. "each HMI control type must resolve to a different descriptor");
  88. require(descriptor->storageName != nullptr
  89. && descriptor->storageName[0] != '\0',
  90. "HMI storage names must not be empty");
  91. require(descriptor->displayName != nullptr
  92. && descriptor->displayName[0] != '\0',
  93. "HMI display names must not be empty");
  94. require(descriptor->idPrefix != nullptr
  95. && descriptor->idPrefix[0] != '\0',
  96. "HMI id prefixes must not be empty");
  97. require(descriptor->defaultText != nullptr,
  98. "HMI default text must not be null");
  99. require(descriptor->defaultBounds.width > 0
  100. && descriptor->defaultBounds.height > 0,
  101. "HMI default bounds must have a positive size");
  102. require(findHmiControlDescriptor(descriptor->storageName) == descriptor,
  103. "HMI storage name lookup must return its registered descriptor");
  104. require(storage_names.emplace(descriptor->storageName).second,
  105. "HMI storage names must be unique");
  106. require(id_prefixes.emplace(descriptor->idPrefix).second,
  107. "HMI id prefixes must be unique");
  108. const std::optional<RegisterArea> binding_area =
  109. hmiBindingArea(descriptor->bindingKind);
  110. switch (descriptor->runtimeValueKind)
  111. {
  112. case HmiRuntimeValueKind::Bit:
  113. {
  114. require(descriptor->bindingKind == HmiBindingKind::Bit
  115. && binding_area == RegisterArea::M,
  116. "bit runtime controls must bind to the M area");
  117. break;
  118. }
  119. case HmiRuntimeValueKind::Word:
  120. {
  121. require(descriptor->bindingKind == HmiBindingKind::Word
  122. && binding_area == RegisterArea::D,
  123. "word runtime controls must bind to the D area");
  124. break;
  125. }
  126. case HmiRuntimeValueKind::None:
  127. {
  128. require(descriptor->bindingKind == HmiBindingKind::None
  129. && !binding_area.has_value(),
  130. "static controls must not declare a register binding");
  131. break;
  132. }
  133. }
  134. require(descriptor->requiresBindingForRunning
  135. == (descriptor->runtimeValueKind
  136. != HmiRuntimeValueKind::None),
  137. "runtime value controls must require a configured binding");
  138. }
  139. require(findHmiControlDescriptor(HmiControlType::Count) == nullptr,
  140. "the HMI control count marker must not be registered");
  141. require(findHmiControlDescriptor(static_cast<HmiControlType>(99)) == nullptr,
  142. "unknown HMI control types must not resolve");
  143. require(findHmiControlDescriptor("unknown") == nullptr,
  144. "unknown HMI storage names must not resolve");
  145. require(hmiBindingArea(HmiBindingKind::Bit) == RegisterArea::M,
  146. "bit bindings must use the M area");
  147. require(hmiBindingArea(HmiBindingKind::Word) == RegisterArea::D,
  148. "word bindings must use the D area");
  149. require(!hmiBindingArea(HmiBindingKind::None).has_value(),
  150. "controls without bindings must not resolve a register area");
  151. }
  152. void testProgressBarConfigurationBoundaries()
  153. {
  154. const HmiProgressBarConfig config{-20, 80, true};
  155. require(config.isValid(), "a progress bar range must accept increasing bounds");
  156. require(config.percentageForValue(-20) == 0,
  157. "progress bar minimum must map to zero percent");
  158. require(config.percentageForValue(30) == 50,
  159. "progress bar midpoint must map to fifty percent");
  160. require(config.percentageForValue(80) == 100,
  161. "progress bar maximum must map to one hundred percent");
  162. require(config.percentageForValue(-100) == 0
  163. && config.percentageForValue(100) == 100,
  164. "progress bar percentages must clamp values outside the range");
  165. HmiProgressBarConfig invalid_range{10, 10, true};
  166. require(!invalid_range.isValid()
  167. && invalid_range.percentageForValue(10) == 0,
  168. "progress bar must reject an empty range defensively");
  169. HmiControl progress;
  170. progress.id = "progress";
  171. progress.type = HmiControlType::ProgressBar;
  172. progress.progressBar = config;
  173. require(progress.validate(),
  174. "an unbound progress bar with valid configuration must remain a valid draft");
  175. require(!progress.isConfigured(),
  176. "an unbound progress bar must not be ready for running");
  177. progress.binding = RegisterAddress{RegisterArea::D, 0};
  178. require(progress.validate() && progress.isConfigured(),
  179. "a progress bar with a D binding must be ready for running");
  180. progress.progressBar->maximumValue = progress.progressBar->minimumValue;
  181. require(!progress.validate(),
  182. "a progress bar with an invalid range must be rejected");
  183. progress.progressBar = config;
  184. progress.binding = RegisterAddress{RegisterArea::M, 0};
  185. require(!progress.validate(),
  186. "a progress bar must reject an M binding");
  187. }
  188. Project makeValidProject();
  189. void testHmiAppearancePropertyBoundaries()
  190. {
  191. // 外观属性必须在领域层拒绝格式错误,但不能影响未知扩展属性
  192. Project project = makeValidProject();
  193. HmiControl &button = project.hmiPages.front().controls.front();
  194. button.properties[HmiAppearanceProperty::kTextColor] = "#E53935";
  195. button.properties[HmiAppearanceProperty::kFontSize] = "18";
  196. button.properties[HmiAppearanceProperty::kFontBold] = "true";
  197. button.properties[HmiAppearanceProperty::kFontItalic] = "false";
  198. require(project.validate(), "valid HMI appearance properties must pass validation");
  199. button.properties[HmiAppearanceProperty::kTextColor] = "red";
  200. require(!project.validate(), "text colors must use the #RRGGBB format");
  201. project = makeValidProject();
  202. HmiControl &font_control = project.hmiPages.front().controls.front();
  203. font_control.properties[HmiAppearanceProperty::kFontSize] = "5";
  204. require(!project.validate(), "font sizes below the minimum must be rejected");
  205. font_control.properties[HmiAppearanceProperty::kFontSize] = "73";
  206. require(!project.validate(), "font sizes above the maximum must be rejected");
  207. font_control.properties[HmiAppearanceProperty::kFontSize] = "large";
  208. require(!project.validate(), "non-numeric font sizes must be rejected");
  209. project = makeValidProject();
  210. HmiControl &style_control = project.hmiPages.front().controls.front();
  211. style_control.properties[HmiAppearanceProperty::kFontBold] = "yes";
  212. require(!project.validate(), "font style flags must be true or false");
  213. project = makeValidProject();
  214. project.hmiPages.front().controls.front().properties["legacyColor"] = "green";
  215. require(project.validate(), "unknown HMI extension properties must remain supported");
  216. }
  217. Project makeValidProject()
  218. {
  219. // 构造包含 HMI 绑定和完整梯形图网络的最小合法工程作为测试基线
  220. HmiControl start_button;
  221. start_button.id = "start-button";
  222. start_button.type = HmiControlType::Button;
  223. start_button.text = "Start";
  224. start_button.binding = {RegisterArea::M, 0};
  225. HmiPage page;
  226. page.id = "main-page";
  227. page.name = "Main";
  228. page.controls.push_back(start_button);
  229. LogicNode contact;
  230. contact.id = "start-contact";
  231. contact.config = ContactNodeConfig{
  232. RegisterAddress{RegisterArea::M, 0},
  233. ContactMode::NormallyOpen};
  234. LogicNode coil;
  235. coil.id = "run-coil";
  236. coil.config = CoilNodeConfig{
  237. RegisterAddress{RegisterArea::M, 1},
  238. CoilMode::Normal};
  239. ControlLogic logic;
  240. logic.id = "start-logic";
  241. logic.name = "Start logic";
  242. LadderRung rung;
  243. rung.id = "rung-1";
  244. rung.name = "Network 1";
  245. rung.condition = ConditionExpression::fromNode(contact);
  246. rung.output = coil;
  247. logic.rungs.push_back(rung);
  248. Project project;
  249. project.metadata = {"sample-project", "Sample project", "1.0"};
  250. project.hmiPages.push_back(page);
  251. project.initialHmiPageId = page.id;
  252. project.controlLogics.push_back(logic);
  253. return project;
  254. }
  255. void testMultiPageAndLogicDomainRules()
  256. {
  257. Project project = makeValidProject();
  258. HmiPage settings;
  259. settings.id = "settings-page";
  260. settings.name = "Settings";
  261. project.hmiPages.push_back(settings);
  262. HmiControl label;
  263. label.id = "title";
  264. label.type = HmiControlType::Label;
  265. label.text = "Machine";
  266. project.hmiPages.front().controls.push_back(label);
  267. require(project.validate(), "an unbound label must be a valid static control");
  268. project.hmiPages.front().controls.back().binding =
  269. RegisterAddress{RegisterArea::M, 10};
  270. require(!project.validate(), "labels must reject register bindings");
  271. project = makeValidProject();
  272. project.hmiPages.push_back(settings);
  273. HmiControl jump;
  274. jump.id = "settings-jump";
  275. jump.type = HmiControlType::PageJump;
  276. jump.text = "Settings";
  277. jump.pageJump = HmiPageJumpConfig{settings.id};
  278. project.hmiPages.front().controls.push_back(jump);
  279. require(project.validate() && project.validateForRunning(),
  280. "a page jump must resolve its target by stable page id");
  281. project.hmiPages.front().controls.back().pageJump->targetPageId = "missing";
  282. require(!project.validate(), "a page jump must reject a missing target page");
  283. project = makeValidProject();
  284. project.initialHmiPageId = "missing";
  285. require(!project.validate(), "the initial HMI page id must resolve to a page");
  286. project = makeValidProject();
  287. HmiPage duplicate_name = settings;
  288. duplicate_name.name = project.hmiPages.front().name;
  289. project.hmiPages.push_back(duplicate_name);
  290. require(!project.validate(), "HMI page names must be unique");
  291. project = makeValidProject();
  292. ControlLogic disabled_draft;
  293. disabled_draft.id = "draft-logic";
  294. disabled_draft.name = "Draft logic";
  295. disabled_draft.enabled = false;
  296. disabled_draft.rungs.push_back(
  297. {"rung-1", "Draft network", {}, std::nullopt, std::nullopt});
  298. project.controlLogics.push_back(disabled_draft);
  299. require(project.validateForRunning(),
  300. "a disabled draft logic must not block offline running");
  301. project.controlLogics.back().name = project.controlLogics.front().name;
  302. require(!project.validate(), "control logic names must be unique");
  303. project = makeValidProject();
  304. project.hmiPages.front().controls.front().type =
  305. static_cast<HmiControlType>(99);
  306. project.hmiPages.front().controls.front().binding.reset();
  307. require(!project.validate(), "unknown HMI control types must be rejected");
  308. }
  309. void testQuantityBoundaries()
  310. {
  311. Project project = makeValidProject();
  312. for (std::size_t index = 1U; index < ProjectLimits::kMaximumHmiPages; ++index)
  313. {
  314. project.hmiPages.push_back({
  315. "page-" + std::to_string(index),
  316. "Page " + std::to_string(index),
  317. 800,
  318. 400,
  319. {}});
  320. }
  321. require(project.validate(), "an HMI page count of 128 must be accepted");
  322. project.hmiPages.push_back({"page-over", "Page over", 800, 400, {}});
  323. require(!project.validate(), "an HMI page count of 129 must be rejected");
  324. project = makeValidProject();
  325. project.hmiPages.front().controls.clear();
  326. for (std::size_t index = 0U;
  327. index < ProjectLimits::kMaximumHmiControlsPerPage;
  328. ++index)
  329. {
  330. HmiControl label;
  331. label.id = "label-" + std::to_string(index);
  332. label.type = HmiControlType::Label;
  333. label.bounds = {0, 0, 1, 1};
  334. label.text = "label";
  335. project.hmiPages.front().controls.push_back(std::move(label));
  336. }
  337. require(project.validate(), "a page control count of 512 must be accepted");
  338. HmiControl extra_label;
  339. extra_label.id = "label-over";
  340. extra_label.type = HmiControlType::Label;
  341. extra_label.bounds = {0, 0, 1, 1};
  342. extra_label.text = "label";
  343. project.hmiPages.front().controls.push_back(std::move(extra_label));
  344. require(!project.validate(), "a page control count of 513 must be rejected");
  345. project = makeValidProject();
  346. project.hmiPages.front().width = ProjectLimits::kMaximumHmiPageWidth;
  347. project.hmiPages.front().height = ProjectLimits::kMaximumHmiPageHeight;
  348. require(project.validate(), "an HMI page size of 1600 by 800 must be accepted");
  349. project.hmiPages.front().width = ProjectLimits::kMaximumHmiPageWidth + 1;
  350. require(!project.validate(), "an HMI page width of 1601 must be rejected");
  351. project.hmiPages.front().width = ProjectLimits::kMinimumHmiPageWidth - 1;
  352. require(!project.validate(), "an HMI page width of 319 must be rejected");
  353. project.hmiPages.front().width = ProjectLimits::kMaximumHmiPageWidth;
  354. project.hmiPages.front().height = ProjectLimits::kMinimumHmiPageHeight - 1;
  355. require(!project.validate(), "an HMI page height of 199 must be rejected");
  356. ConditionExpression leaf = ConditionExpression::fromNode({
  357. "depth-node-0",
  358. ContactNodeConfig{RegisterAddress{RegisterArea::M, 0}},
  359. true});
  360. std::function<ConditionExpression(int, int *)> makeNested =
  361. [&makeNested](int depth, int *next_address)
  362. {
  363. if (depth == 1)
  364. {
  365. const int address = (*next_address)++;
  366. return ConditionExpression::fromNode({
  367. "depth-node-" + std::to_string(address),
  368. ContactNodeConfig{RegisterAddress{RegisterArea::M, address}},
  369. true});
  370. }
  371. const int address = (*next_address)++;
  372. ConditionExpression expression;
  373. expression.id = "depth-expression-" + std::to_string(address);
  374. expression.kind = depth % 2 == 0
  375. ? ConditionExpressionKind::Parallel
  376. : ConditionExpressionKind::Series;
  377. expression.children = {
  378. makeNested(depth - 1, next_address),
  379. ConditionExpression::fromNode({
  380. "depth-node-" + std::to_string(address),
  381. ContactNodeConfig{RegisterAddress{RegisterArea::M, address}},
  382. true})};
  383. return expression;
  384. };
  385. int next_address = 1;
  386. ConditionExpression maximum_depth = makeNested(
  387. static_cast<int>(ProjectLimits::kMaximumExpressionDepth), &next_address);
  388. require(maximum_depth.validate(),
  389. "an expression depth of 20 must be accepted");
  390. ConditionExpression excessive_depth = makeNested(
  391. static_cast<int>(ProjectLimits::kMaximumExpressionDepth) + 1,
  392. &next_address);
  393. require(!excessive_depth.validate(),
  394. "an expression depth of 21 must be rejected");
  395. CounterNodeConfig counter_config{
  396. CounterAddress{0},
  397. CounterMode::Up,
  398. RegisterAddress{RegisterArea::D, 0},
  399. WordOperand{WordOperandKind::Constant, RegisterAddress{RegisterArea::D, 0}, -1},
  400. RegisterAddress{RegisterArea::M, 0}};
  401. LogicNode counter{"counter-negative-preset", counter_config, true};
  402. require(!counter.validate(), "a negative constant counter preset must be rejected");
  403. (void)leaf;
  404. }
  405. void testLogicNodeConfigurationBoundaries()
  406. {
  407. // 触点只能绑定 M 区,数值比较只能绑定 D 区
  408. LogicNode contact;
  409. contact.id = "contact";
  410. contact.config = ContactNodeConfig{
  411. RegisterAddress{RegisterArea::M, 0},
  412. ContactMode::NormallyOpen};
  413. require(contact.validate(), "contact node bound to M address must be valid");
  414. contact.config = ContactNodeConfig{
  415. RegisterAddress{RegisterArea::D, 0},
  416. ContactMode::NormallyOpen};
  417. require(!contact.validate(), "contact node bound to D address must be rejected");
  418. LogicNode comparison;
  419. comparison.id = "comparison";
  420. comparison.config = CompareNodeConfig{
  421. RegisterAddress{RegisterArea::D, 0},
  422. ComparisonOperator::GreaterThan,
  423. static_cast<std::int16_t>(100)};
  424. require(comparison.validate(), "comparison node bound to D address must be valid");
  425. }
  426. void testTimerAndCommentBoundaries()
  427. {
  428. LogicNode edge;
  429. edge.id = "edge";
  430. edge.config = EdgeContactNodeConfig{
  431. RegisterAddress{RegisterArea::M, 0}, EdgeMode::Rising};
  432. require(edge.validate(), "a valid rising edge contact must pass validation");
  433. LogicNode timer_contact;
  434. timer_contact.id = "timer-contact";
  435. timer_contact.config = TimerContactNodeConfig{
  436. TimerAddress{4000}, ContactMode::NormallyOpen};
  437. require(timer_contact.validate(), "T4000 must be a valid timer contact");
  438. timer_contact.config = TimerContactNodeConfig{
  439. TimerAddress{-1}, ContactMode::NormallyOpen};
  440. require(!timer_contact.validate(), "a negative T address must be rejected");
  441. LogicNode ton;
  442. ton.id = "ton";
  443. ton.config = TonNodeConfig{TimerAddress{0}, TonNodeConfig::kMinimumPresetMs};
  444. require(ton.validate(), "the minimum TON preset must be valid");
  445. ton.config = TonNodeConfig{TimerAddress{0}, 0};
  446. require(!ton.validate(), "a zero TON preset must be rejected");
  447. ton.config = TonNodeConfig{
  448. TimerAddress{0}, TonNodeConfig::kMaximumPresetMs + 1};
  449. require(!ton.validate(), "an oversized TON preset must be rejected");
  450. RegisterComment comment{RegisterAddress{RegisterArea::M, 0}, "启动按钮"};
  451. require(comment.validate(), "a nonblank register comment must be valid");
  452. comment.text.assign(ProjectLimits::kMaximumRegisterCommentBytes, 'a');
  453. require(comment.validate(), "a register comment at the byte limit must be valid");
  454. comment.text.push_back('a');
  455. require(!comment.validate(), "a register comment above the byte limit must fail");
  456. comment.text = "启动\n按钮";
  457. require(!comment.validate(), "a multiline register comment must be rejected");
  458. comment.text = "启动\r按钮";
  459. require(!comment.validate(), "a register comment containing CR must be rejected");
  460. comment.text = " \t";
  461. require(!comment.validate(), "a blank register comment must be rejected");
  462. LadderRung comment_rung;
  463. comment_rung.id = "comment-rung";
  464. comment_rung.name = "Comment rung";
  465. comment_rung.comment.assign(ProjectLimits::kMaximumRungCommentBytes, 'a');
  466. require(comment_rung.validate(), "a rung comment at the byte limit must be valid");
  467. comment_rung.comment.push_back('a');
  468. require(!comment_rung.validate(), "a rung comment above the byte limit must fail");
  469. comment_rung.comment = "第一行\n第二行";
  470. require(!comment_rung.validate(), "a multiline rung comment must be rejected");
  471. comment_rung.comment = "第一行\r第二行";
  472. require(!comment_rung.validate(), "a rung comment containing CR must be rejected");
  473. Project project = makeValidProject();
  474. project.registerComments = {
  475. {RegisterAddress{RegisterArea::M, 0}, "启动按钮"},
  476. {RegisterAddress{RegisterArea::M, 0}, "重复地址"}};
  477. require(!project.validate(), "duplicate register comments must be rejected");
  478. }
  479. LadderRung makeTimerRung(
  480. const std::string &rung_id,
  481. const std::string &condition_id,
  482. const std::string &output_id,
  483. int timer_index,
  484. int preset_ms)
  485. {
  486. LogicNode condition;
  487. condition.id = condition_id;
  488. condition.config = ContactNodeConfig{
  489. RegisterAddress{RegisterArea::M, timer_index}, ContactMode::NormallyOpen};
  490. LogicNode output;
  491. output.id = output_id;
  492. output.config = TonNodeConfig{TimerAddress{timer_index}, preset_ms};
  493. LadderRung rung;
  494. rung.id = rung_id;
  495. rung.name = rung_id;
  496. rung.condition = ConditionExpression::fromNode(condition);
  497. rung.output = output;
  498. return rung;
  499. }
  500. void testTimerReferencesForRunning()
  501. {
  502. ControlLogic valid;
  503. valid.id = "timer-valid";
  504. valid.name = "Timer valid";
  505. valid.rungs.push_back(makeTimerRung("rung-0", "input-0", "ton-0", 0, 100));
  506. require(validateTimerReferencesForRunning({valid}),
  507. "a timer contact-free TON network must pass timer reference validation");
  508. ControlLogic duplicate = valid;
  509. duplicate.id = "timer-duplicate";
  510. duplicate.name = "Timer duplicate";
  511. duplicate.rungs.front().output->id = "ton-duplicate";
  512. require(!validateTimerReferencesForRunning({valid, duplicate}),
  513. "the same T must not have two enabled TON drivers");
  514. ControlLogic missing;
  515. missing.id = "timer-missing";
  516. missing.name = "Timer missing";
  517. LogicNode contact;
  518. contact.id = "missing-contact";
  519. contact.config = TimerContactNodeConfig{
  520. TimerAddress{7}, ContactMode::NormallyOpen};
  521. LogicNode output;
  522. output.id = "missing-coil";
  523. output.config = CoilNodeConfig{
  524. RegisterAddress{RegisterArea::M, 7}, CoilMode::Normal};
  525. LadderRung missing_rung;
  526. missing_rung.id = "missing-rung";
  527. missing_rung.name = "Missing rung";
  528. missing_rung.condition = ConditionExpression::fromNode(contact);
  529. missing_rung.output = output;
  530. missing.rungs.push_back(missing_rung);
  531. require(!validateTimerReferencesForRunning({missing}),
  532. "a T contact without an enabled TON driver must be rejected");
  533. missing.enabled = false;
  534. require(validateTimerReferencesForRunning({missing}),
  535. "disabled timer drafts must not block runtime timer validation");
  536. }
  537. LadderRung makeCounterRung(
  538. const std::string &rung_id,
  539. const std::string &output_id,
  540. int counter_index)
  541. {
  542. LogicNode condition;
  543. condition.id = rung_id + "-input";
  544. condition.config = ContactNodeConfig{
  545. RegisterAddress{RegisterArea::M, counter_index},
  546. ContactMode::NormallyOpen};
  547. LogicNode output;
  548. output.id = output_id;
  549. output.config = CounterNodeConfig{
  550. CounterAddress{counter_index},
  551. CounterMode::Up,
  552. RegisterAddress{RegisterArea::D, counter_index},
  553. WordOperand{
  554. WordOperandKind::Constant,
  555. RegisterAddress{RegisterArea::D, 0},
  556. 10},
  557. RegisterAddress{RegisterArea::M, counter_index + 1}};
  558. LadderRung rung;
  559. rung.id = rung_id;
  560. rung.name = rung_id;
  561. rung.condition = ConditionExpression::fromNode(condition);
  562. rung.output = output;
  563. return rung;
  564. }
  565. void testCounterAndDataInstructionBoundaries()
  566. {
  567. require(CounterAddress{0}.isValid() && CounterAddress{4000}.isValid(),
  568. "C0 and C4000 must be valid counter resources");
  569. require(!CounterAddress{-1}.isValid() && !CounterAddress{4001}.isValid(),
  570. "counter resources outside 0 through 4000 must be rejected");
  571. LogicNode counter;
  572. counter.id = "counter";
  573. counter.config = CounterNodeConfig{
  574. CounterAddress{0},
  575. CounterMode::Up,
  576. RegisterAddress{RegisterArea::D, 10},
  577. WordOperand{
  578. WordOperandKind::Register,
  579. RegisterAddress{RegisterArea::D, 11},
  580. 0},
  581. RegisterAddress{RegisterArea::M, 12}};
  582. require(counter.validate(),
  583. "a counter with C identity and external M/D addresses must be valid");
  584. CounterNodeConfig invalid_counter = std::get<CounterNodeConfig>(counter.config);
  585. invalid_counter.currentValueAddress = RegisterAddress{RegisterArea::M, 10};
  586. counter.config = invalid_counter;
  587. require(!counter.validate(), "counter CV must reject M addresses");
  588. LogicNode move;
  589. move.id = "move";
  590. move.config = MoveNodeConfig{
  591. WordOperand{
  592. WordOperandKind::Constant,
  593. RegisterAddress{RegisterArea::D, 0},
  594. -100},
  595. RegisterAddress{RegisterArea::D, 20}};
  596. require(move.validate() && move.isOutput(),
  597. "MOVE with a constant source and D destination must be a valid output");
  598. LogicNode add;
  599. add.id = "add";
  600. add.config = ArithmeticNodeConfig{
  601. ArithmeticOperation::Add,
  602. WordOperand{
  603. WordOperandKind::Register,
  604. RegisterAddress{RegisterArea::D, 20},
  605. 0},
  606. WordOperand{
  607. WordOperandKind::Constant,
  608. RegisterAddress{RegisterArea::D, 0},
  609. 1},
  610. RegisterAddress{RegisterArea::D, 20}};
  611. require(add.validate() && add.isOutput(),
  612. "ADD must allow the same D register as source and destination");
  613. ControlLogic valid;
  614. valid.id = "counter-valid";
  615. valid.name = "Counter valid";
  616. valid.rungs.push_back(makeCounterRung("counter-rung", "ctu-0", 0));
  617. require(validateCounterReferencesForRunning({valid}),
  618. "a counter output without contacts must pass reference validation");
  619. ControlLogic duplicate = valid;
  620. duplicate.id = "counter-duplicate";
  621. duplicate.name = "Counter duplicate";
  622. duplicate.rungs.front().output->id = "ctu-duplicate";
  623. require(!validateCounterReferencesForRunning({valid, duplicate}),
  624. "the same C resource must not have multiple enabled drivers");
  625. ControlLogic missing;
  626. missing.id = "counter-missing";
  627. missing.name = "Counter missing";
  628. LogicNode missing_contact;
  629. missing_contact.id = "missing-counter-contact";
  630. missing_contact.config = CounterContactNodeConfig{
  631. CounterAddress{7}, ContactMode::NormallyOpen};
  632. LogicNode output;
  633. output.id = "missing-counter-coil";
  634. output.config = CoilNodeConfig{
  635. RegisterAddress{RegisterArea::M, 7}, CoilMode::Normal};
  636. LadderRung missing_rung;
  637. missing_rung.id = "missing-counter-rung";
  638. missing_rung.name = "Missing counter rung";
  639. missing_rung.condition = ConditionExpression::fromNode(missing_contact);
  640. missing_rung.output = output;
  641. missing.rungs.push_back(missing_rung);
  642. require(!validateCounterReferencesForRunning({missing}),
  643. "a C contact without an enabled counter driver must be rejected");
  644. }
  645. void testLadderLogicBoundaries()
  646. {
  647. LogicNode stop;
  648. stop.id = "stop";
  649. stop.config = ContactNodeConfig{
  650. RegisterAddress{RegisterArea::M, 1},
  651. ContactMode::NormallyClosed};
  652. LogicNode start;
  653. start.id = "start";
  654. start.config = ContactNodeConfig{
  655. RegisterAddress{RegisterArea::M, 0},
  656. ContactMode::NormallyOpen};
  657. LogicNode run_contact;
  658. run_contact.id = "run-contact";
  659. run_contact.config = ContactNodeConfig{
  660. RegisterAddress{RegisterArea::M, 1},
  661. ContactMode::NormallyOpen};
  662. LogicNode coil;
  663. coil.id = "run-coil";
  664. coil.config = CoilNodeConfig{
  665. RegisterAddress{RegisterArea::M, 1},
  666. CoilMode::Normal};
  667. ControlLogic logic;
  668. logic.id = "hold-logic";
  669. logic.name = "Hold logic";
  670. ConditionExpression start_parallel;
  671. start_parallel.id = "parallel-start";
  672. start_parallel.kind = ConditionExpressionKind::Parallel;
  673. start_parallel.children = {
  674. ConditionExpression::fromNode(start),
  675. ConditionExpression::fromNode(run_contact)};
  676. ConditionExpression root;
  677. root.id = "series-root";
  678. root.kind = ConditionExpressionKind::Series;
  679. root.children = {
  680. ConditionExpression::fromNode(stop),
  681. start_parallel};
  682. LadderRung rung;
  683. rung.id = "rung-1";
  684. rung.name = "Self hold";
  685. rung.condition = root;
  686. rung.output = coil;
  687. logic.rungs.push_back(rung);
  688. require(logic.validate(), "stop AND (start OR run) self-hold ladder must be valid");
  689. ConditionExpression wire = ConditionExpression::fromWire("wire-1", 2);
  690. require(wire.validate() && wire.validateForRunning()
  691. && wire.wire->columnSpan == 2,
  692. "a configured horizontal wire must be a valid runnable expression leaf");
  693. ConditionExpression invalid_wire = ConditionExpression::fromWire("wire-invalid", 0);
  694. require(!invalid_wire.validate(), "a zero-column horizontal wire must be rejected");
  695. invalid_wire = ConditionExpression::fromWire(
  696. "wire-too-wide", WireSegment::kMaximumColumnSpan + 1);
  697. require(!invalid_wire.validate(), "an oversized horizontal wire must be rejected");
  698. ConditionExpression maximum_columns;
  699. maximum_columns.id = "maximum-columns";
  700. maximum_columns.kind = ConditionExpressionKind::Series;
  701. for (int column = 0; column < ProjectLimits::kMaximumConditionColumns; ++column)
  702. {
  703. LogicNode node;
  704. node.id = "column-" + std::to_string(column + 1);
  705. node.config = ContactNodeConfig{
  706. RegisterAddress{RegisterArea::M, column},
  707. ContactMode::NormallyOpen};
  708. maximum_columns.children.push_back(
  709. ConditionExpression::fromNode(std::move(node)));
  710. }
  711. require(maximum_columns.validate(),
  712. "ten condition columns must be accepted");
  713. LogicNode extra_column;
  714. extra_column.id = "column-11";
  715. extra_column.config = ContactNodeConfig{
  716. RegisterAddress{RegisterArea::M, 10},
  717. ContactMode::NormallyOpen};
  718. maximum_columns.children.push_back(
  719. ConditionExpression::fromNode(std::move(extra_column)));
  720. require(!maximum_columns.validate(),
  721. "an eleventh condition column must be rejected");
  722. ConditionExpression wired_series;
  723. wired_series.id = "wired-series";
  724. wired_series.kind = ConditionExpressionKind::Series;
  725. wired_series.children = {
  726. ConditionExpression::fromNode(stop),
  727. ConditionExpression::fromWire("wire-series"),
  728. start_parallel};
  729. require(wired_series.validateForRunning(),
  730. "a wire must preserve a valid structured series expression");
  731. logic.rungs.front().condition->children.front() =
  732. ConditionExpression::fromNode(coil);
  733. require(!logic.validate(), "a ladder condition expression must reject coils");
  734. logic.rungs.front().condition = root;
  735. logic.rungs.front().output = start;
  736. require(!logic.validate(), "a ladder output must be a coil");
  737. logic.rungs.front().output.reset();
  738. require(logic.validate(), "incomplete ladder may remain in an editable draft");
  739. require(!logic.validateForRunning(),
  740. "conditions without an output must block runtime validation");
  741. LadderRung empty_rung{
  742. "rung-empty", "Empty network", {}, std::nullopt, std::nullopt};
  743. require(empty_rung.validate(), "an empty editing network must be valid");
  744. empty_rung.output = coil;
  745. require(empty_rung.validate(), "output-only network may remain in an editable draft");
  746. require(empty_rung.validateForRunning(),
  747. "an output-only network must be valid as an unconditional rung");
  748. logic.rungs.front().output = coil;
  749. logic.rungs.front().condition = root;
  750. logic.rungs.front().condition->children.at(1).children.at(1).node->id = start.id;
  751. require(!logic.validate(), "logic node ids must be unique");
  752. ConditionExpression nested_parallel;
  753. nested_parallel.id = "parallel-nested";
  754. nested_parallel.kind = ConditionExpressionKind::Parallel;
  755. nested_parallel.children = {
  756. ConditionExpression::fromNode(start),
  757. root};
  758. require(nested_parallel.validate(),
  759. "nested series and parallel expressions must be valid");
  760. }
  761. void testModelsValidateBindingsAndIdentifiers()
  762. {
  763. // 聚合验证必须拒绝错误绑定、重复标识和越界控件
  764. Project project = makeValidProject();
  765. require(project.validate(), "valid project model must pass validation");
  766. project.hmiPages.front().controls.front().binding =
  767. RegisterAddress{RegisterArea::D, 0};
  768. require(!project.validate(), "button bound to D area must be rejected");
  769. project = makeValidProject();
  770. project.hmiPages.push_back(project.hmiPages.front());
  771. require(!project.validate(), "duplicate HMI page id must be rejected");
  772. project = makeValidProject();
  773. project.hmiPages.front().controls.front().bounds.x = -1;
  774. require(!project.validate(), "controls outside the page must be rejected");
  775. project = makeValidProject();
  776. project.hmiPages.front().controls.front().bounds.width = 801;
  777. require(!project.validate(), "controls wider than the page must be rejected");
  778. project = makeValidProject();
  779. project.hmiPages.front().controls.front().properties.emplace("", "value");
  780. require(!project.validate(), "empty HMI property names must be rejected");
  781. project = makeValidProject();
  782. project.hmiPages.front().controls.front().binding.reset();
  783. require(project.validate(), "unbound HMI control must be accepted in a draft");
  784. require(!project.validateForRunning(),
  785. "unbound HMI control must block runtime validation");
  786. project = makeValidProject();
  787. project.controlLogics.front().rungs.front().output->configured = false;
  788. require(project.validate(), "unconfigured ladder node must be accepted in a draft");
  789. require(!project.validateForRunning(),
  790. "unconfigured ladder node must block runtime validation");
  791. }
  792. void testRuntimeStateBoundaries()
  793. {
  794. // 运行模式测试覆盖离线和真机的互斥及 PLC 首读前置条件
  795. RuntimeState state;
  796. require(state.policy().allowsProjectEditing, "editing mode must allow project editing");
  797. require(state.enterOfflineRunning().succeeded, "editing may enter offline running");
  798. require(state.policy().usesVirtualRegisters, "offline mode must use virtual registers");
  799. require(state.policy().runsLogicExecutor, "offline mode must run logic executor");
  800. require(state.enterOnlineRunning(true).error
  801. == ModeTransitionError::MustReturnToEditing,
  802. "offline mode must not directly enter online mode");
  803. require(state.enterEditing().succeeded, "offline mode may return to editing");
  804. require(state.enterOnlineRunning(false).error
  805. == ModeTransitionError::InitialPlcReadRequired,
  806. "online mode must require an initial PLC read");
  807. require(state.enterOnlineRunning(true).succeeded,
  808. "editing may enter online mode after initial PLC read");
  809. require(!state.policy().runsLogicExecutor,
  810. "online mode must keep the software logic executor stopped");
  811. require(state.policy().usesPlcRegisters, "online mode must use PLC registers");
  812. }
  813. } // namespace
  814. int main()
  815. {
  816. try
  817. {
  818. // 每个测试函数独立覆盖一个领域边界,首个异常即终止测试进程
  819. testRegisterAddressBoundaries();
  820. testRegisterAddressParsing();
  821. testRegisterRepositorySeparatesAreas();
  822. testHmiControlRegistryCompleteness();
  823. testProgressBarConfigurationBoundaries();
  824. testHmiAppearancePropertyBoundaries();
  825. testLogicNodeConfigurationBoundaries();
  826. testTimerAndCommentBoundaries();
  827. testTimerReferencesForRunning();
  828. testCounterAndDataInstructionBoundaries();
  829. testLadderLogicBoundaries();
  830. testModelsValidateBindingsAndIdentifiers();
  831. testMultiPageAndLogicDomainRules();
  832. testQuantityBoundaries();
  833. testRuntimeStateBoundaries();
  834. }
  835. catch (const std::exception &error)
  836. {
  837. std::cerr << "domain tests failed: " << error.what() << '\n';
  838. return 1;
  839. }
  840. std::cout << "domain tests passed\n";
  841. return 0;
  842. }