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

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