综合平台编程器项目的远程存储
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

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