综合平台编程器项目的远程存储
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.
 
 
 
 

734 rivejä
31 KiB

  1. #include "domain/active_register_repository.h"
  2. #include "domain/project_storage.h"
  3. #include "domain/register_repository.h"
  4. #include "services/hmi_editor_service.h"
  5. #include "services/hmi_runtime_service.h"
  6. #include "services/logic_editor_service.h"
  7. #include "services/offline_simulation_service.h"
  8. #include "services/project_service.h"
  9. #include "services/runtime_mode_service.h"
  10. #include "services/register_monitor_service.h"
  11. #include "ui/hmi_editor_widget.h"
  12. #include "ui/free_monitor_widget.h"
  13. #include "ui/logic_editor_widget.h"
  14. #include "ui/main_window.h"
  15. #include "ui/plc_connection_dialog.h"
  16. #include <QAction>
  17. #include <QApplication>
  18. #include <QComboBox>
  19. #include <QDialog>
  20. #include <QDockWidget>
  21. #include <QGraphicsItem>
  22. #include <QGraphicsScene>
  23. #include <QImage>
  24. #include <QLabel>
  25. #include <QLineEdit>
  26. #include <QListWidget>
  27. #include <QPainter>
  28. #include <QSpinBox>
  29. #include <QPushButton>
  30. #include <QTableWidget>
  31. #include <QTimer>
  32. #include <QTest>
  33. #include <iostream>
  34. #include <stdexcept>
  35. #include <string>
  36. namespace {
  37. class TestProjectStorage final : public ProjectStorage
  38. {
  39. public:
  40. // 主窗口测试使用无副作用存储实现,隔离文件对 UI 行为的影响
  41. ProjectSaveResult save(const Project &, const std::string &) override
  42. {
  43. return {true, ProjectStorageError::None, {}};
  44. }
  45. ProjectLoadResult load(const std::string &) override
  46. {
  47. return {false, {}, ProjectStorageError::FileReadFailed, {}};
  48. }
  49. };
  50. class RepeatedStatusGateway final : public PlcCommunicationGateway
  51. {
  52. public:
  53. PlcCommunicationResult connectDevice(
  54. const PlcSerialConfiguration &) override
  55. {
  56. connection_state = PlcConnectionState::Connecting;
  57. notifyStateChanged();
  58. connection_state = PlcConnectionState::Connected;
  59. notifyStateChanged();
  60. notifyStateChanged();
  61. return {true, {}};
  62. }
  63. void disconnectDevice() override
  64. {
  65. connection_state = PlcConnectionState::Disconnected;
  66. notifyStateChanged();
  67. }
  68. void setPollAddresses(const std::vector<RegisterAddress> &) override {}
  69. PlcConnectionState state() const override { return connection_state; }
  70. bool initialReadCompleted() const override { return false; }
  71. PlcCommunicationError lastErrorType() const override
  72. {
  73. return PlcCommunicationError::None;
  74. }
  75. const std::string &lastError() const override { return last_error; }
  76. void setCallbacks(
  77. std::function<void()> state_callback,
  78. std::function<void(bool)> initial_callback,
  79. std::function<void()> cache_callback,
  80. std::function<void(const std::string &)> error_callback) override
  81. {
  82. state_changed = std::move(state_callback);
  83. initial_read_changed = std::move(initial_callback);
  84. cache_updated = std::move(cache_callback);
  85. error_reported = std::move(error_callback);
  86. }
  87. private:
  88. void notifyStateChanged()
  89. {
  90. if (state_changed)
  91. {
  92. state_changed();
  93. }
  94. }
  95. PlcConnectionState connection_state = PlcConnectionState::Disconnected;
  96. std::string last_error;
  97. std::function<void()> state_changed;
  98. std::function<void(bool)> initial_read_changed;
  99. std::function<void()> cache_updated;
  100. std::function<void(const std::string &)> error_reported;
  101. };
  102. class OnlineReadyGateway final : public PlcCommunicationGateway
  103. {
  104. public:
  105. PlcCommunicationResult connectDevice(const PlcSerialConfiguration &) override
  106. {
  107. connection_state = PlcConnectionState::Connected;
  108. if (state_changed)
  109. {
  110. state_changed();
  111. }
  112. return {true, {}};
  113. }
  114. void disconnectDevice() override
  115. {
  116. connection_state = PlcConnectionState::Disconnected;
  117. initial_read = false;
  118. if (initial_read_changed)
  119. {
  120. initial_read_changed(false);
  121. }
  122. if (state_changed)
  123. {
  124. state_changed();
  125. }
  126. }
  127. void setPollAddresses(const std::vector<RegisterAddress> &addresses) override
  128. {
  129. poll_addresses = addresses;
  130. }
  131. PlcConnectionState state() const override { return connection_state; }
  132. bool initialReadCompleted() const override { return initial_read; }
  133. PlcCommunicationError lastErrorType() const override { return last_error_type; }
  134. const std::string &lastError() const override { return last_error; }
  135. void setCallbacks(
  136. std::function<void()> state_callback,
  137. std::function<void(bool)> initial_callback,
  138. std::function<void()> cache_callback,
  139. std::function<void(const std::string &)> error_callback) override
  140. {
  141. state_changed = std::move(state_callback);
  142. initial_read_changed = std::move(initial_callback);
  143. cache_updated = std::move(cache_callback);
  144. error_reported = std::move(error_callback);
  145. }
  146. void completeInitialRead()
  147. {
  148. initial_read = true;
  149. if (initial_read_changed)
  150. {
  151. initial_read_changed(true);
  152. }
  153. }
  154. void failCommunication(
  155. PlcCommunicationError error_type, const std::string &message)
  156. {
  157. initial_read = false;
  158. last_error_type = error_type;
  159. last_error = message;
  160. connection_state = PlcConnectionState::Faulted;
  161. if (initial_read_changed)
  162. {
  163. initial_read_changed(false);
  164. }
  165. if (state_changed)
  166. {
  167. state_changed();
  168. }
  169. if (error_reported)
  170. {
  171. error_reported(last_error);
  172. }
  173. }
  174. PlcConnectionState connection_state = PlcConnectionState::Disconnected;
  175. bool initial_read = false;
  176. PlcCommunicationError last_error_type = PlcCommunicationError::None;
  177. std::string last_error;
  178. std::vector<RegisterAddress> poll_addresses;
  179. std::function<void()> state_changed;
  180. std::function<void(bool)> initial_read_changed;
  181. std::function<void()> cache_updated;
  182. std::function<void(const std::string &)> error_reported;
  183. };
  184. void require(bool condition, const std::string &message)
  185. {
  186. if (!condition)
  187. {
  188. throw std::runtime_error(message);
  189. }
  190. }
  191. template<typename ObjectType>
  192. ObjectType *requiredChild(MainWindow &window, const char *name)
  193. {
  194. // 通过 objectName 取得 Designer 组件,缺失时给出明确测试失败信息
  195. ObjectType *child = window.findChild<ObjectType *>(QString::fromLatin1(name));
  196. require(child != nullptr, std::string("missing UI object ") + name);
  197. return child;
  198. }
  199. QColor renderedColorAt(HmiEditorWidget &view, const QPoint &viewport_position)
  200. {
  201. QImage image(view.viewport()->size(), QImage::Format_ARGB32_Premultiplied);
  202. image.fill(Qt::transparent);
  203. QPainter painter(&image);
  204. view.viewport()->render(&painter);
  205. return image.pixelColor(viewport_position);
  206. }
  207. void testRuntimeButtonMouseInteraction()
  208. {
  209. TestProjectStorage storage;
  210. ProjectService project_service(storage);
  211. HmiEditorService editor_service(project_service);
  212. VirtualRegisterRepository repository;
  213. HmiRuntimeService runtime_service(repository);
  214. const HmiEditorResult page_result = editor_service.ensureDefaultPage();
  215. require(page_result.succeeded, "runtime button test must create an HMI page");
  216. const HmiEditorResult button_result = editor_service.addControl(
  217. page_result.id, HmiControlType::Button);
  218. require(button_result.succeeded, "runtime button test must create a button");
  219. HmiControl button = *editor_service.findControl(page_result.id, button_result.id);
  220. button.binding = RegisterAddress{RegisterArea::M, 0};
  221. button.buttonOperation = HmiButtonOperation::MomentaryOn;
  222. require(editor_service.updateControl(page_result.id, button.id, button).succeeded,
  223. "runtime button test must bind the button to M0");
  224. HmiEditorWidget view(editor_service, runtime_service);
  225. view.resize(900, 600);
  226. view.setPageId(page_result.id);
  227. view.setEditingEnabled(false);
  228. view.setRuntimeActive(true);
  229. view.setRuntimeWriteEnabled(true);
  230. view.show();
  231. QApplication::processEvents();
  232. const QPoint center = view.mapFromScene(QPointF(
  233. button.bounds.x + button.bounds.width / 2.0,
  234. button.bounds.y + button.bounds.height / 2.0));
  235. const QPoint color_sample = view.mapFromScene(QPointF(
  236. button.bounds.x + 8.0, button.bounds.y + 8.0));
  237. const QColor normal_color = renderedColorAt(view, color_sample);
  238. QTest::mouseMove(view.viewport(), center);
  239. QApplication::processEvents();
  240. QGraphicsItem *button_item = view.itemAt(center);
  241. require(button_item != nullptr,
  242. "runtime button must be hit-testable while writes are enabled");
  243. require(button_item->cursor().shape() == Qt::PointingHandCursor,
  244. "runtime button must use a pointing-hand cursor");
  245. const QColor hovered_color = renderedColorAt(view, color_sample);
  246. require(hovered_color != normal_color,
  247. "hovering a runtime button must change its visual state");
  248. QTest::mousePress(view.viewport(), Qt::LeftButton, Qt::NoModifier, center);
  249. QApplication::processEvents();
  250. require(repository.readBit({RegisterArea::M, 0}).value,
  251. "pressing a momentary runtime button must write M0 ON");
  252. require(view.scene()->selectedItems().isEmpty(),
  253. "pressing a runtime button must not show an editing selection");
  254. const QColor pressed_color = renderedColorAt(view, color_sample);
  255. require(pressed_color != hovered_color,
  256. "pressing a runtime button must change its visual state");
  257. QTest::mouseRelease(view.viewport(), Qt::LeftButton, Qt::NoModifier, center);
  258. QApplication::processEvents();
  259. require(!repository.readBit({RegisterArea::M, 0}).value,
  260. "releasing a momentary runtime button must write M0 OFF");
  261. require(renderedColorAt(view, color_sample) == hovered_color,
  262. "releasing a runtime button must restore its hovered visual state");
  263. view.setRuntimeWriteEnabled(false);
  264. QApplication::processEvents();
  265. const QColor disabled_color = renderedColorAt(view, color_sample);
  266. require(disabled_color != hovered_color,
  267. "a non-writable runtime button must use its disabled visual state");
  268. QTest::mouseClick(view.viewport(), Qt::LeftButton, Qt::NoModifier, center);
  269. require(!repository.readBit({RegisterArea::M, 0}).value,
  270. "a disabled runtime button must not write its register");
  271. }
  272. void testModeActionsControlEditingAvailability()
  273. {
  274. // 验证模式动作会同步禁用编辑入口,并在失败时恢复当前选择
  275. TestProjectStorage storage;
  276. ProjectService project_service(storage);
  277. HmiEditorService editor_service(project_service);
  278. LogicEditorService logic_editor_service(project_service);
  279. VirtualRegisterRepository repository;
  280. HmiRuntimeService runtime_service(repository);
  281. OfflineSimulationService simulation_service(repository);
  282. RuntimeModeService mode_service(project_service, simulation_service);
  283. RegisterMonitorService monitor_service(repository);
  284. MainWindow window(
  285. mode_service,
  286. project_service,
  287. editor_service,
  288. logic_editor_service,
  289. runtime_service,
  290. monitor_service);
  291. window.resize(1000, 640);
  292. window.show();
  293. QApplication::processEvents();
  294. require(window.findChild<QWidget *>(QStringLiteral("dataPointDock")) == nullptr,
  295. "the removed data point dock must not remain in the main window");
  296. require(window.findChild<QWidget *>(QStringLiteral("hmiDataPointComboBox")) == nullptr
  297. && window.findChild<QWidget *>(QStringLiteral("logicDataPointComboBox")) == nullptr,
  298. "HMI and ladder properties must use direct M/D address inputs");
  299. QAction *editing_action = requiredChild<QAction>(window, "editingModeAction");
  300. QAction *offline_action = requiredChild<QAction>(window, "offlineModeAction");
  301. QAction *online_action = requiredChild<QAction>(window, "onlineModeAction");
  302. QAction *add_button_action = requiredChild<QAction>(window, "addButtonAction");
  303. QAction *add_indicator_action = requiredChild<QAction>(window, "addIndicatorAction");
  304. QAction *delete_control_action = requiredChild<QAction>(window, "deleteControlAction");
  305. QAction *add_normally_open_action = requiredChild<QAction>(
  306. window, "addNormallyOpenAction");
  307. QAction *add_normal_coil_action = requiredChild<QAction>(
  308. window, "addNormalCoilAction");
  309. QAction *parallel_insert_action = requiredChild<QAction>(
  310. window, "parallelInsertAction");
  311. QDockWidget *project_dock = requiredChild<QDockWidget>(window, "projectDock");
  312. QDockWidget *properties_dock = requiredChild<QDockWidget>(window, "propertiesDock");
  313. QLabel *selection = requiredChild<QLabel>(window, "selectionValueLabel");
  314. QLineEdit *text_edit = requiredChild<QLineEdit>(window, "controlTextEdit");
  315. QComboBox *button_operation = requiredChild<QComboBox>(
  316. window, "buttonOperationComboBox");
  317. QPushButton *apply_properties = requiredChild<QPushButton>(
  318. window, "applyPropertiesButton");
  319. HmiEditorWidget *hmi_editor = requiredChild<HmiEditorWidget>(
  320. window, "hmiEditorWidget");
  321. QLabel *executor_status = requiredChild<QLabel>(window, "executorStatusLabel");
  322. QWidget *runtime_tab = requiredChild<QWidget>(window, "runtimeMonitorTab");
  323. QWidget *runtime_hmi = requiredChild<QWidget>(window, "runtimeHmiView");
  324. QWidget *runtime_logic = requiredChild<QWidget>(window, "runtimeLogicView");
  325. QWidget *free_monitor = requiredChild<QWidget>(window, "freeMonitorWidget");
  326. require(!runtime_tab->isVisible(),
  327. "runtime monitor workspace must be hidden while editing");
  328. const qreal compact_scale = hmi_editor->transform().m11();
  329. window.resize(1600, 900);
  330. QApplication::processEvents();
  331. require(hmi_editor->transform().m11() > compact_scale,
  332. "HMI page must refit when the window becomes larger");
  333. require(editing_action->isChecked(), "editing action must be selected initially");
  334. require(project_dock->isEnabled(), "project dock must be enabled while editing");
  335. require(properties_dock->isEnabled(), "properties dock must be enabled while editing");
  336. add_button_action->trigger();
  337. const std::string page_id = editor_service.firstPageId();
  338. require(editor_service.findPage(page_id)->controls.size() == 1,
  339. "adding a control must update the HMI page model");
  340. require(selection->text() == QStringLiteral("button-1(未绑定)"),
  341. "an unbound added control must be marked in the property panel");
  342. require(text_edit->text() == QStringLiteral("按钮"),
  343. "property panel must show the control text");
  344. require(button_operation->currentText() == QStringLiteral("瞬时 ON"),
  345. "new HMI buttons must default to momentary ON");
  346. const QList<QGraphicsItem *> unbound_items = hmi_editor->scene()->selectedItems();
  347. require(unbound_items.size() == 1 && unbound_items.front()->boundingRect().top() == 0,
  348. "an unbound HMI control must not reserve an address label area");
  349. button_operation->setCurrentIndex(
  350. button_operation->findData(static_cast<int>(HmiButtonOperation::Toggle)));
  351. apply_properties->click();
  352. require(editor_service.findControl(page_id, "button-1")->buttonOperation
  353. == HmiButtonOperation::Toggle,
  354. "the property panel must update the HMI button operation");
  355. HmiControl bound_button = *editor_service.findControl(page_id, "button-1");
  356. bound_button.binding = RegisterAddress{RegisterArea::M, 0};
  357. require(editor_service.updateControl(page_id, bound_button.id, bound_button).succeeded,
  358. "binding an HMI button to M0 must succeed");
  359. hmi_editor->reloadPage();
  360. hmi_editor->selectControl(bound_button.id);
  361. const QList<QGraphicsItem *> bound_items = hmi_editor->scene()->selectedItems();
  362. require(bound_items.size() == 1 && bound_items.front()->boundingRect().top() < 0,
  363. "a bound HMI control must include its address label above the control body");
  364. delete_control_action->trigger();
  365. require(editor_service.findPage(page_id)->controls.empty(),
  366. "deleting a selected control must update the HMI page model");
  367. add_indicator_action->trigger();
  368. HmiControl runtime_indicator = *editor_service.findControl(page_id, "indicator-1");
  369. runtime_indicator.binding = RegisterAddress{RegisterArea::M, 3};
  370. require(editor_service.updateControl(
  371. page_id, runtime_indicator.id, runtime_indicator).succeeded,
  372. "a configured HMI control must be available for the runtime projection");
  373. hmi_editor->reloadPage();
  374. add_normally_open_action->trigger();
  375. parallel_insert_action->trigger();
  376. add_normal_coil_action->trigger();
  377. const ControlLogic *logic = logic_editor_service.findLogic(
  378. logic_editor_service.firstLogicId());
  379. require(logic != nullptr && logic->rungs.size() == 1,
  380. "logic actions must edit the default ladder rung");
  381. require(logic->rungs.front().condition.has_value()
  382. && logic->rungs.front().condition->kind
  383. == ConditionExpressionKind::Parallel
  384. && logic->rungs.front().condition->children.size() == 2U,
  385. "parallel branch action must create a parallel expression");
  386. require(logic->rungs.front().output.has_value(),
  387. "coil action must set the fixed ladder output");
  388. offline_action->trigger();
  389. require(mode_service.mode() == ApplicationMode::Editing,
  390. "unconfigured ladder nodes must block offline running");
  391. const LadderRung &rung = logic->rungs.front();
  392. std::vector<const LogicNode *> condition_nodes;
  393. collectConditionNodes(*rung.condition, &condition_nodes);
  394. for (const LogicNode *node : condition_nodes)
  395. {
  396. require(logic_editor_service.updateNodeConfig(
  397. logic_editor_service.firstLogicId(),
  398. node->id,
  399. ContactNodeConfig{
  400. RegisterAddress{RegisterArea::M, 0},
  401. ContactMode::NormallyOpen})
  402. .succeeded,
  403. "applying a contact configuration must complete the ladder node");
  404. }
  405. require(logic_editor_service.updateNodeConfig(
  406. logic_editor_service.firstLogicId(),
  407. rung.output->id,
  408. CoilNodeConfig{
  409. RegisterAddress{RegisterArea::M, 1},
  410. CoilMode::Normal})
  411. .succeeded,
  412. "applying a coil configuration must complete the ladder node");
  413. offline_action->trigger();
  414. require(mode_service.mode() == ApplicationMode::OfflineRunning,
  415. "offline action must enter offline running");
  416. require(simulation_service.state() == SimulationState::Running,
  417. "offline action must start the actual simulation service");
  418. require(executor_status->text().contains(QStringLiteral("运行")),
  419. "executor status label must report the actual running state");
  420. require(!project_dock->isEnabled(),
  421. "project dock must be disabled while running");
  422. require(!properties_dock->isEnabled(),
  423. "properties dock must be disabled while running");
  424. require(!add_button_action->isEnabled(),
  425. "HMI add controls must be disabled while running");
  426. require(!add_normally_open_action->isEnabled(),
  427. "logic add nodes must be disabled while running");
  428. require(runtime_tab->isVisible() && runtime_hmi->isVisible()
  429. && runtime_logic->isVisible() && free_monitor->isVisible(),
  430. "offline running must show HMI, ladder trace and free monitor together");
  431. auto *runtime_hmi_view = qobject_cast<HmiEditorWidget *>(runtime_hmi);
  432. require(runtime_hmi_view != nullptr
  433. && runtime_hmi_view->scene()->items().size() == 2,
  434. "offline runtime HMI must project the configured page control");
  435. QLineEdit *monitor_address = requiredChild<QLineEdit>(window, "addressEdit");
  436. QPushButton *monitor_add = requiredChild<QPushButton>(window, "addButton");
  437. QTableWidget *monitor_table = requiredChild<QTableWidget>(window, "monitorTable");
  438. monitor_address->setText(QStringLiteral("M0"));
  439. monitor_add->click();
  440. repository.writeBit({RegisterArea::M, 0}, true);
  441. auto *monitor_widget = requiredChild<FreeMonitorWidget>(window, "freeMonitorWidget");
  442. monitor_widget->refreshValues(
  443. ApplicationMode::OfflineRunning, PlcConnectionState::Disconnected);
  444. require(monitor_table->rowCount() == 1
  445. && monitor_table->item(0, 2)->text() == QStringLiteral("ON"),
  446. "offline free monitor must read the same virtual M/D repository as HMI");
  447. online_action->trigger();
  448. require(mode_service.mode() == ApplicationMode::OfflineRunning,
  449. "running modes must not switch directly through the UI");
  450. require(offline_action->isChecked(),
  451. "failed mode changes must restore the active action");
  452. editing_action->trigger();
  453. require(mode_service.mode() == ApplicationMode::Editing,
  454. "editing action must return to editing");
  455. require(simulation_service.state() == SimulationState::Stopped,
  456. "editing action must stop the simulation service");
  457. require(executor_status->text() == QStringLiteral("逻辑执行器:停止"),
  458. "executor status label must report the actual stopped state");
  459. require(project_dock->isEnabled(),
  460. "project dock must be restored after returning to editing");
  461. require(properties_dock->isEnabled(),
  462. "properties dock must be restored after returning to editing");
  463. require(add_button_action->isEnabled(),
  464. "HMI add controls must be restored after returning to editing");
  465. require(add_normally_open_action->isEnabled(),
  466. "logic add nodes must be restored after returning to editing");
  467. require(!runtime_tab->isVisible(),
  468. "returning to editing must hide the runtime monitor workspace");
  469. online_action->trigger();
  470. require(mode_service.mode() == ApplicationMode::Editing,
  471. "online action must require an initial PLC read");
  472. require(editing_action->isChecked(),
  473. "rejected online running must restore the editing action");
  474. }
  475. void testPlcConfigurationUsesDialog()
  476. {
  477. PlcSerialConfiguration initial;
  478. initial.portName = "COM17";
  479. initial.serverAddress = 12;
  480. initial.baudRate = 38400;
  481. initial.dataBits = 7;
  482. initial.parity = 3;
  483. initial.stopBits = 2;
  484. initial.responseTimeoutMs = 2500;
  485. initial.retries = 4;
  486. initial.pollIntervalMs = 350;
  487. PlcConnectionDialog configuration_dialog(initial);
  488. const PlcSerialConfiguration actual = configuration_dialog.configuration();
  489. require(actual.portName == initial.portName,
  490. "PLC dialog must preserve a manually entered serial port");
  491. require(actual.serverAddress == initial.serverAddress
  492. && actual.baudRate == initial.baudRate
  493. && actual.dataBits == initial.dataBits
  494. && actual.parity == initial.parity
  495. && actual.stopBits == initial.stopBits,
  496. "PLC dialog must preserve Modbus RTU serial parameters");
  497. require(actual.responseTimeoutMs == initial.responseTimeoutMs
  498. && actual.retries == initial.retries
  499. && actual.pollIntervalMs == initial.pollIntervalMs,
  500. "PLC dialog must preserve communication timing parameters");
  501. TestProjectStorage storage;
  502. ProjectService project_service(storage);
  503. HmiEditorService editor_service(project_service);
  504. LogicEditorService logic_editor_service(project_service);
  505. VirtualRegisterRepository repository;
  506. HmiRuntimeService runtime_service(repository);
  507. OfflineSimulationService simulation_service(repository);
  508. RuntimeModeService mode_service(project_service, simulation_service);
  509. RegisterMonitorService monitor_service(repository);
  510. MainWindow window(
  511. mode_service,
  512. project_service,
  513. editor_service,
  514. logic_editor_service,
  515. runtime_service,
  516. monitor_service);
  517. require(window.findChild<QComboBox *>(QStringLiteral("serialPortComboBox")) == nullptr,
  518. "serial configuration controls must not be embedded in the main window");
  519. QAction *configure_action = requiredChild<QAction>(window, "configurePlcAction");
  520. bool dialog_opened = false;
  521. QTimer::singleShot(
  522. 0,
  523. [&dialog_opened]
  524. {
  525. auto *dialog = qobject_cast<PlcConnectionDialog *>(
  526. QApplication::activeModalWidget());
  527. dialog_opened = dialog != nullptr;
  528. if (dialog != nullptr)
  529. {
  530. dialog->reject();
  531. }
  532. });
  533. configure_action->trigger();
  534. require(dialog_opened,
  535. "PLC configuration action must open the dedicated configuration dialog");
  536. }
  537. void testRepeatedPlcStatusNotificationsAreCoalesced()
  538. {
  539. TestProjectStorage storage;
  540. ProjectService project_service(storage);
  541. HmiEditorService editor_service(project_service);
  542. LogicEditorService logic_editor_service(project_service);
  543. VirtualRegisterRepository virtual_repository;
  544. VirtualRegisterRepository plc_repository;
  545. ActiveRegisterRepository active_repository(virtual_repository);
  546. HmiRuntimeService runtime_service(active_repository);
  547. OfflineSimulationService simulation_service(virtual_repository);
  548. RepeatedStatusGateway gateway;
  549. RuntimeModeService mode_service(project_service, simulation_service);
  550. RegisterMonitorService monitor_service(active_repository);
  551. mode_service.configurePlc(
  552. gateway, active_repository, virtual_repository, plc_repository);
  553. MainWindow window(
  554. mode_service,
  555. project_service,
  556. editor_service,
  557. logic_editor_service,
  558. runtime_service,
  559. monitor_service);
  560. QListWidget *output = requiredChild<QListWidget>(window, "outputList");
  561. const int initial_count = output->count();
  562. const PlcCommunicationResult result = mode_service.connectPlc(
  563. {"COM3", 1, 9600, 8, 2, 1, 1000, 2, 200});
  564. require(result.succeeded, "PLC connection setup must succeed");
  565. QApplication::processEvents();
  566. const QString expected = QStringLiteral("PLC 已连接,正在读取工程使用的 M/D 地址");
  567. int matching_count = 0;
  568. for (int index = initial_count; index < output->count(); ++index)
  569. {
  570. if (output->item(index)->text() == expected)
  571. {
  572. ++matching_count;
  573. }
  574. }
  575. require(matching_count == 1,
  576. "repeated PLC status callbacks must append one coalesced output message");
  577. }
  578. void testOnlineWorkspaceShowsHmiAndFreeMonitorOnly()
  579. {
  580. TestProjectStorage storage;
  581. ProjectService project_service(storage);
  582. HmiEditorService editor_service(project_service);
  583. LogicEditorService logic_editor_service(project_service);
  584. VirtualRegisterRepository virtual_repository;
  585. VirtualRegisterRepository plc_repository;
  586. ActiveRegisterRepository active_repository(virtual_repository);
  587. HmiRuntimeService runtime_service(active_repository);
  588. OfflineSimulationService simulation_service(virtual_repository);
  589. OnlineReadyGateway gateway;
  590. RuntimeModeService mode_service(project_service, simulation_service);
  591. RegisterMonitorService monitor_service(active_repository);
  592. mode_service.configurePlc(
  593. gateway, active_repository, virtual_repository, plc_repository);
  594. MainWindow window(
  595. mode_service,
  596. project_service,
  597. editor_service,
  598. logic_editor_service,
  599. runtime_service,
  600. monitor_service);
  601. window.resize(1200, 760);
  602. window.show();
  603. QApplication::processEvents();
  604. require(mode_service.connectPlc(
  605. {"COM9", 1, 9600, 8, 2, 1, 1000, 2, 200}).succeeded,
  606. "online workspace test must connect the fake PLC gateway");
  607. gateway.completeInitialRead();
  608. QAction *online_action = requiredChild<QAction>(window, "onlineModeAction");
  609. online_action->trigger();
  610. QApplication::processEvents();
  611. QWidget *runtime_tab = requiredChild<QWidget>(window, "runtimeMonitorTab");
  612. QWidget *runtime_hmi = requiredChild<QWidget>(window, "runtimeHmiView");
  613. QWidget *runtime_logic = requiredChild<QWidget>(window, "runtimeLogicView");
  614. QWidget *free_monitor = requiredChild<QWidget>(window, "freeMonitorWidget");
  615. require(mode_service.mode() == ApplicationMode::OnlineRunning,
  616. "completed PLC initial read must allow online running");
  617. require(runtime_tab->isVisible() && runtime_hmi->isVisible()
  618. && free_monitor->isVisible(),
  619. "online running must show HMI and free monitor together");
  620. require(!runtime_logic->isVisible(),
  621. "online running must not show a misleading local ladder runtime trace");
  622. QLineEdit *monitor_address = requiredChild<QLineEdit>(window, "addressEdit");
  623. QPushButton *monitor_add = requiredChild<QPushButton>(window, "addButton");
  624. monitor_address->setText(QStringLiteral("D9"));
  625. monitor_add->click();
  626. require(std::find(
  627. gateway.poll_addresses.begin(),
  628. gateway.poll_addresses.end(),
  629. RegisterAddress{RegisterArea::D, 9}) != gateway.poll_addresses.end(),
  630. "online free monitor addresses must join the active PLC poll set immediately");
  631. QAction *configure_action = requiredChild<QAction>(window, "configurePlcAction");
  632. QAction *disconnect_action = requiredChild<QAction>(window, "disconnectPlcAction");
  633. QListWidget *output = requiredChild<QListWidget>(window, "outputList");
  634. gateway.failCommunication(
  635. PlcCommunicationError::CommunicationTimeout,
  636. "PLC 通信超时,本地串口 COM9 仍处于打开状态;请检查 PLC 供电和 RS-485 接线");
  637. QApplication::processEvents();
  638. require(mode_service.mode() == ApplicationMode::Editing,
  639. "a communication fault must return the UI from online running to editing");
  640. require(configure_action->isEnabled()
  641. && configure_action->text() == QStringLiteral("PLC 重新配置"),
  642. "faulted PLC state must expose direct reconfiguration");
  643. require(disconnect_action->isEnabled(),
  644. "faulted PLC state must still allow explicit serial session cleanup");
  645. require(output->count() > 0
  646. && output->item(output->count() - 1)->text().contains(
  647. QStringLiteral("PLC 通信超时")),
  648. "communication fault details must remain in the output log");
  649. online_action->trigger();
  650. require(mode_service.mode() == ApplicationMode::Editing,
  651. "faulted PLC state must not re-enter online running without a fresh read");
  652. }
  653. } // namespace
  654. int main(int argc, char *argv[])
  655. {
  656. // 无窗口平台使 Qt Widgets 测试可在自动化环境稳定运行
  657. qputenv("QT_QPA_PLATFORM", QByteArrayLiteral("offscreen"));
  658. QApplication application(argc, argv);
  659. try
  660. {
  661. testRuntimeButtonMouseInteraction();
  662. testModeActionsControlEditingAvailability();
  663. testPlcConfigurationUsesDialog();
  664. testRepeatedPlcStatusNotificationsAreCoalesced();
  665. testOnlineWorkspaceShowsHmiAndFreeMonitorOnly();
  666. }
  667. catch (const std::exception &error)
  668. {
  669. std::cerr << "main window tests failed: " << error.what() << '\n';
  670. return 1;
  671. }
  672. std::cout << "main window tests passed\n";
  673. return 0;
  674. }