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

562 line
23 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 <QLabel>
  24. #include <QLineEdit>
  25. #include <QListWidget>
  26. #include <QSpinBox>
  27. #include <QPushButton>
  28. #include <QTableWidget>
  29. #include <QTimer>
  30. #include <iostream>
  31. #include <stdexcept>
  32. #include <string>
  33. namespace {
  34. class TestProjectStorage final : public ProjectStorage
  35. {
  36. public:
  37. // 主窗口测试使用无副作用存储实现,隔离文件对 UI 行为的影响
  38. ProjectSaveResult save(const Project &, const std::string &) override
  39. {
  40. return {true, ProjectStorageError::None, {}};
  41. }
  42. ProjectLoadResult load(const std::string &) override
  43. {
  44. return {false, {}, ProjectStorageError::FileReadFailed, {}};
  45. }
  46. };
  47. class RepeatedStatusGateway final : public PlcCommunicationGateway
  48. {
  49. public:
  50. PlcCommunicationResult connectDevice(
  51. const PlcSerialConfiguration &) override
  52. {
  53. connection_state = PlcConnectionState::Connecting;
  54. notifyStateChanged();
  55. connection_state = PlcConnectionState::Connected;
  56. notifyStateChanged();
  57. notifyStateChanged();
  58. return {true, {}};
  59. }
  60. void disconnectDevice() override
  61. {
  62. connection_state = PlcConnectionState::Disconnected;
  63. notifyStateChanged();
  64. }
  65. void setPollAddresses(const std::vector<RegisterAddress> &) override {}
  66. PlcConnectionState state() const override { return connection_state; }
  67. bool initialReadCompleted() const override { return false; }
  68. const std::string &lastError() const override { return last_error; }
  69. void setCallbacks(
  70. std::function<void()> state_callback,
  71. std::function<void(bool)> initial_callback,
  72. std::function<void()> cache_callback,
  73. std::function<void(const std::string &)> error_callback) override
  74. {
  75. state_changed = std::move(state_callback);
  76. initial_read_changed = std::move(initial_callback);
  77. cache_updated = std::move(cache_callback);
  78. error_reported = std::move(error_callback);
  79. }
  80. private:
  81. void notifyStateChanged()
  82. {
  83. if (state_changed)
  84. {
  85. state_changed();
  86. }
  87. }
  88. PlcConnectionState connection_state = PlcConnectionState::Disconnected;
  89. std::string last_error;
  90. std::function<void()> state_changed;
  91. std::function<void(bool)> initial_read_changed;
  92. std::function<void()> cache_updated;
  93. std::function<void(const std::string &)> error_reported;
  94. };
  95. class OnlineReadyGateway final : public PlcCommunicationGateway
  96. {
  97. public:
  98. PlcCommunicationResult connectDevice(const PlcSerialConfiguration &) override
  99. {
  100. connection_state = PlcConnectionState::Connected;
  101. if (state_changed)
  102. {
  103. state_changed();
  104. }
  105. return {true, {}};
  106. }
  107. void disconnectDevice() override
  108. {
  109. connection_state = PlcConnectionState::Disconnected;
  110. }
  111. void setPollAddresses(const std::vector<RegisterAddress> &addresses) override
  112. {
  113. poll_addresses = addresses;
  114. }
  115. PlcConnectionState state() const override { return connection_state; }
  116. bool initialReadCompleted() const override { return initial_read; }
  117. const std::string &lastError() const override { return last_error; }
  118. void setCallbacks(
  119. std::function<void()> state_callback,
  120. std::function<void(bool)> initial_callback,
  121. std::function<void()> cache_callback,
  122. std::function<void(const std::string &)> error_callback) override
  123. {
  124. state_changed = std::move(state_callback);
  125. initial_read_changed = std::move(initial_callback);
  126. cache_updated = std::move(cache_callback);
  127. error_reported = std::move(error_callback);
  128. }
  129. void completeInitialRead()
  130. {
  131. initial_read = true;
  132. if (initial_read_changed)
  133. {
  134. initial_read_changed(true);
  135. }
  136. }
  137. PlcConnectionState connection_state = PlcConnectionState::Disconnected;
  138. bool initial_read = false;
  139. std::string last_error;
  140. std::vector<RegisterAddress> poll_addresses;
  141. std::function<void()> state_changed;
  142. std::function<void(bool)> initial_read_changed;
  143. std::function<void()> cache_updated;
  144. std::function<void(const std::string &)> error_reported;
  145. };
  146. void require(bool condition, const std::string &message)
  147. {
  148. if (!condition)
  149. {
  150. throw std::runtime_error(message);
  151. }
  152. }
  153. template<typename ObjectType>
  154. ObjectType *requiredChild(MainWindow &window, const char *name)
  155. {
  156. // 通过 objectName 取得 Designer 组件,缺失时给出明确测试失败信息
  157. ObjectType *child = window.findChild<ObjectType *>(QString::fromLatin1(name));
  158. require(child != nullptr, std::string("missing UI object ") + name);
  159. return child;
  160. }
  161. void testModeActionsControlEditingAvailability()
  162. {
  163. // 验证模式动作会同步禁用编辑入口,并在失败时恢复当前选择
  164. TestProjectStorage storage;
  165. ProjectService project_service(storage);
  166. HmiEditorService editor_service(project_service);
  167. LogicEditorService logic_editor_service(project_service);
  168. VirtualRegisterRepository repository;
  169. HmiRuntimeService runtime_service(repository);
  170. OfflineSimulationService simulation_service(repository);
  171. RuntimeModeService mode_service(project_service, simulation_service);
  172. RegisterMonitorService monitor_service(repository);
  173. MainWindow window(
  174. mode_service,
  175. project_service,
  176. editor_service,
  177. logic_editor_service,
  178. runtime_service,
  179. monitor_service);
  180. window.resize(1000, 640);
  181. window.show();
  182. QApplication::processEvents();
  183. require(window.findChild<QWidget *>(QStringLiteral("dataPointDock")) == nullptr,
  184. "the removed data point dock must not remain in the main window");
  185. require(window.findChild<QWidget *>(QStringLiteral("hmiDataPointComboBox")) == nullptr
  186. && window.findChild<QWidget *>(QStringLiteral("logicDataPointComboBox")) == nullptr,
  187. "HMI and ladder properties must use direct M/D address inputs");
  188. QAction *editing_action = requiredChild<QAction>(window, "editingModeAction");
  189. QAction *offline_action = requiredChild<QAction>(window, "offlineModeAction");
  190. QAction *online_action = requiredChild<QAction>(window, "onlineModeAction");
  191. QAction *add_button_action = requiredChild<QAction>(window, "addButtonAction");
  192. QAction *delete_control_action = requiredChild<QAction>(window, "deleteControlAction");
  193. QAction *add_normally_open_action = requiredChild<QAction>(
  194. window, "addNormallyOpenAction");
  195. QAction *add_normal_coil_action = requiredChild<QAction>(
  196. window, "addNormalCoilAction");
  197. QAction *parallel_insert_action = requiredChild<QAction>(
  198. window, "parallelInsertAction");
  199. QDockWidget *project_dock = requiredChild<QDockWidget>(window, "projectDock");
  200. QDockWidget *properties_dock = requiredChild<QDockWidget>(window, "propertiesDock");
  201. QLabel *selection = requiredChild<QLabel>(window, "selectionValueLabel");
  202. QLineEdit *text_edit = requiredChild<QLineEdit>(window, "controlTextEdit");
  203. HmiEditorWidget *hmi_editor = requiredChild<HmiEditorWidget>(
  204. window, "hmiEditorWidget");
  205. QLabel *executor_status = requiredChild<QLabel>(window, "executorStatusLabel");
  206. QWidget *runtime_tab = requiredChild<QWidget>(window, "runtimeMonitorTab");
  207. QWidget *runtime_hmi = requiredChild<QWidget>(window, "runtimeHmiView");
  208. QWidget *runtime_logic = requiredChild<QWidget>(window, "runtimeLogicView");
  209. QWidget *free_monitor = requiredChild<QWidget>(window, "freeMonitorWidget");
  210. require(!runtime_tab->isVisible(),
  211. "runtime monitor workspace must be hidden while editing");
  212. const qreal compact_scale = hmi_editor->transform().m11();
  213. window.resize(1600, 900);
  214. QApplication::processEvents();
  215. require(hmi_editor->transform().m11() > compact_scale,
  216. "HMI page must refit when the window becomes larger");
  217. require(editing_action->isChecked(), "editing action must be selected initially");
  218. require(project_dock->isEnabled(), "project dock must be enabled while editing");
  219. require(properties_dock->isEnabled(), "properties dock must be enabled while editing");
  220. add_button_action->trigger();
  221. const std::string page_id = editor_service.firstPageId();
  222. require(editor_service.findPage(page_id)->controls.size() == 1,
  223. "adding a control must update the HMI page model");
  224. require(selection->text() == QStringLiteral("button-1(未绑定)"),
  225. "an unbound added control must be marked in the property panel");
  226. require(text_edit->text() == QStringLiteral("按钮"),
  227. "property panel must show the control text");
  228. const QList<QGraphicsItem *> unbound_items = hmi_editor->scene()->selectedItems();
  229. require(unbound_items.size() == 1 && unbound_items.front()->boundingRect().top() == 0,
  230. "an unbound HMI control must not reserve an address label area");
  231. HmiControl bound_button = *editor_service.findControl(page_id, "button-1");
  232. bound_button.binding = RegisterAddress{RegisterArea::M, 0};
  233. require(editor_service.updateControl(page_id, bound_button.id, bound_button).succeeded,
  234. "binding an HMI button to M0 must succeed");
  235. hmi_editor->reloadPage();
  236. hmi_editor->selectControl(bound_button.id);
  237. const QList<QGraphicsItem *> bound_items = hmi_editor->scene()->selectedItems();
  238. require(bound_items.size() == 1 && bound_items.front()->boundingRect().top() < 0,
  239. "a bound HMI control must include its address label above the control body");
  240. delete_control_action->trigger();
  241. require(editor_service.findPage(page_id)->controls.empty(),
  242. "deleting a selected control must update the HMI page model");
  243. add_normally_open_action->trigger();
  244. parallel_insert_action->trigger();
  245. add_normal_coil_action->trigger();
  246. const ControlLogic *logic = logic_editor_service.findLogic(
  247. logic_editor_service.firstLogicId());
  248. require(logic != nullptr && logic->rungs.size() == 1,
  249. "logic actions must edit the default ladder rung");
  250. require(logic->rungs.front().condition.has_value()
  251. && logic->rungs.front().condition->kind
  252. == ConditionExpressionKind::Parallel
  253. && logic->rungs.front().condition->children.size() == 2U,
  254. "parallel branch action must create a parallel expression");
  255. require(logic->rungs.front().output.has_value(),
  256. "coil action must set the fixed ladder output");
  257. offline_action->trigger();
  258. require(mode_service.mode() == ApplicationMode::Editing,
  259. "unconfigured ladder nodes must block offline running");
  260. const LadderRung &rung = logic->rungs.front();
  261. std::vector<const LogicNode *> condition_nodes;
  262. collectConditionNodes(*rung.condition, &condition_nodes);
  263. for (const LogicNode *node : condition_nodes)
  264. {
  265. require(logic_editor_service.updateNodeConfig(
  266. logic_editor_service.firstLogicId(),
  267. node->id,
  268. ContactNodeConfig{
  269. RegisterAddress{RegisterArea::M, 0},
  270. ContactMode::NormallyOpen})
  271. .succeeded,
  272. "applying a contact configuration must complete the ladder node");
  273. }
  274. require(logic_editor_service.updateNodeConfig(
  275. logic_editor_service.firstLogicId(),
  276. rung.output->id,
  277. CoilNodeConfig{
  278. RegisterAddress{RegisterArea::M, 1},
  279. CoilMode::Normal})
  280. .succeeded,
  281. "applying a coil configuration must complete the ladder node");
  282. offline_action->trigger();
  283. require(mode_service.mode() == ApplicationMode::OfflineRunning,
  284. "offline action must enter offline running");
  285. require(simulation_service.state() == SimulationState::Running,
  286. "offline action must start the actual simulation service");
  287. require(executor_status->text().contains(QStringLiteral("运行")),
  288. "executor status label must report the actual running state");
  289. require(!project_dock->isEnabled(),
  290. "project dock must be disabled while running");
  291. require(!properties_dock->isEnabled(),
  292. "properties dock must be disabled while running");
  293. require(!add_button_action->isEnabled(),
  294. "HMI add controls must be disabled while running");
  295. require(!add_normally_open_action->isEnabled(),
  296. "logic add nodes must be disabled while running");
  297. require(runtime_tab->isVisible() && runtime_hmi->isVisible()
  298. && runtime_logic->isVisible() && free_monitor->isVisible(),
  299. "offline running must show HMI, ladder trace and free monitor together");
  300. QLineEdit *monitor_address = requiredChild<QLineEdit>(window, "addressEdit");
  301. QPushButton *monitor_add = requiredChild<QPushButton>(window, "addButton");
  302. QTableWidget *monitor_table = requiredChild<QTableWidget>(window, "monitorTable");
  303. monitor_address->setText(QStringLiteral("M0"));
  304. monitor_add->click();
  305. repository.writeBit({RegisterArea::M, 0}, true);
  306. auto *monitor_widget = requiredChild<FreeMonitorWidget>(window, "freeMonitorWidget");
  307. monitor_widget->refreshValues(
  308. ApplicationMode::OfflineRunning, PlcConnectionState::Disconnected);
  309. require(monitor_table->rowCount() == 1
  310. && monitor_table->item(0, 2)->text() == QStringLiteral("ON"),
  311. "offline free monitor must read the same virtual M/D repository as HMI");
  312. online_action->trigger();
  313. require(mode_service.mode() == ApplicationMode::OfflineRunning,
  314. "running modes must not switch directly through the UI");
  315. require(offline_action->isChecked(),
  316. "failed mode changes must restore the active action");
  317. editing_action->trigger();
  318. require(mode_service.mode() == ApplicationMode::Editing,
  319. "editing action must return to editing");
  320. require(simulation_service.state() == SimulationState::Stopped,
  321. "editing action must stop the simulation service");
  322. require(executor_status->text() == QStringLiteral("逻辑执行器:停止"),
  323. "executor status label must report the actual stopped state");
  324. require(project_dock->isEnabled(),
  325. "project dock must be restored after returning to editing");
  326. require(properties_dock->isEnabled(),
  327. "properties dock must be restored after returning to editing");
  328. require(add_button_action->isEnabled(),
  329. "HMI add controls must be restored after returning to editing");
  330. require(add_normally_open_action->isEnabled(),
  331. "logic add nodes must be restored after returning to editing");
  332. require(!runtime_tab->isVisible(),
  333. "returning to editing must hide the runtime monitor workspace");
  334. online_action->trigger();
  335. require(mode_service.mode() == ApplicationMode::Editing,
  336. "online action must require an initial PLC read");
  337. require(editing_action->isChecked(),
  338. "rejected online running must restore the editing action");
  339. }
  340. void testPlcConfigurationUsesDialog()
  341. {
  342. PlcSerialConfiguration initial;
  343. initial.portName = "COM17";
  344. initial.serverAddress = 12;
  345. initial.baudRate = 38400;
  346. initial.dataBits = 7;
  347. initial.parity = 3;
  348. initial.stopBits = 2;
  349. initial.responseTimeoutMs = 2500;
  350. initial.retries = 4;
  351. initial.pollIntervalMs = 350;
  352. PlcConnectionDialog configuration_dialog(initial);
  353. const PlcSerialConfiguration actual = configuration_dialog.configuration();
  354. require(actual.portName == initial.portName,
  355. "PLC dialog must preserve a manually entered serial port");
  356. require(actual.serverAddress == initial.serverAddress
  357. && actual.baudRate == initial.baudRate
  358. && actual.dataBits == initial.dataBits
  359. && actual.parity == initial.parity
  360. && actual.stopBits == initial.stopBits,
  361. "PLC dialog must preserve Modbus RTU serial parameters");
  362. require(actual.responseTimeoutMs == initial.responseTimeoutMs
  363. && actual.retries == initial.retries
  364. && actual.pollIntervalMs == initial.pollIntervalMs,
  365. "PLC dialog must preserve communication timing parameters");
  366. TestProjectStorage storage;
  367. ProjectService project_service(storage);
  368. HmiEditorService editor_service(project_service);
  369. LogicEditorService logic_editor_service(project_service);
  370. VirtualRegisterRepository repository;
  371. HmiRuntimeService runtime_service(repository);
  372. OfflineSimulationService simulation_service(repository);
  373. RuntimeModeService mode_service(project_service, simulation_service);
  374. RegisterMonitorService monitor_service(repository);
  375. MainWindow window(
  376. mode_service,
  377. project_service,
  378. editor_service,
  379. logic_editor_service,
  380. runtime_service,
  381. monitor_service);
  382. require(window.findChild<QComboBox *>(QStringLiteral("serialPortComboBox")) == nullptr,
  383. "serial configuration controls must not be embedded in the main window");
  384. QAction *configure_action = requiredChild<QAction>(window, "configurePlcAction");
  385. bool dialog_opened = false;
  386. QTimer::singleShot(
  387. 0,
  388. [&dialog_opened]
  389. {
  390. auto *dialog = qobject_cast<PlcConnectionDialog *>(
  391. QApplication::activeModalWidget());
  392. dialog_opened = dialog != nullptr;
  393. if (dialog != nullptr)
  394. {
  395. dialog->reject();
  396. }
  397. });
  398. configure_action->trigger();
  399. require(dialog_opened,
  400. "PLC configuration action must open the dedicated configuration dialog");
  401. }
  402. void testRepeatedPlcStatusNotificationsAreCoalesced()
  403. {
  404. TestProjectStorage storage;
  405. ProjectService project_service(storage);
  406. HmiEditorService editor_service(project_service);
  407. LogicEditorService logic_editor_service(project_service);
  408. VirtualRegisterRepository virtual_repository;
  409. VirtualRegisterRepository plc_repository;
  410. ActiveRegisterRepository active_repository(virtual_repository);
  411. HmiRuntimeService runtime_service(active_repository);
  412. OfflineSimulationService simulation_service(virtual_repository);
  413. RuntimeModeService mode_service(project_service, simulation_service);
  414. RegisterMonitorService monitor_service(active_repository);
  415. RepeatedStatusGateway gateway;
  416. mode_service.configurePlc(
  417. gateway, active_repository, virtual_repository, plc_repository);
  418. MainWindow window(
  419. mode_service,
  420. project_service,
  421. editor_service,
  422. logic_editor_service,
  423. runtime_service,
  424. monitor_service);
  425. QListWidget *output = requiredChild<QListWidget>(window, "outputList");
  426. const int initial_count = output->count();
  427. const PlcCommunicationResult result = mode_service.connectPlc(
  428. {"COM3", 1, 9600, 8, 2, 1, 1000, 2, 200});
  429. require(result.succeeded, "PLC connection setup must succeed");
  430. QApplication::processEvents();
  431. const QString expected = QStringLiteral("PLC 已连接,正在读取工程使用的 M/D 地址");
  432. int matching_count = 0;
  433. for (int index = initial_count; index < output->count(); ++index)
  434. {
  435. if (output->item(index)->text() == expected)
  436. {
  437. ++matching_count;
  438. }
  439. }
  440. require(matching_count == 1,
  441. "repeated PLC status callbacks must append one coalesced output message");
  442. }
  443. void testOnlineWorkspaceShowsHmiAndFreeMonitorOnly()
  444. {
  445. TestProjectStorage storage;
  446. ProjectService project_service(storage);
  447. HmiEditorService editor_service(project_service);
  448. LogicEditorService logic_editor_service(project_service);
  449. VirtualRegisterRepository virtual_repository;
  450. VirtualRegisterRepository plc_repository;
  451. ActiveRegisterRepository active_repository(virtual_repository);
  452. HmiRuntimeService runtime_service(active_repository);
  453. OfflineSimulationService simulation_service(virtual_repository);
  454. RuntimeModeService mode_service(project_service, simulation_service);
  455. RegisterMonitorService monitor_service(active_repository);
  456. OnlineReadyGateway gateway;
  457. mode_service.configurePlc(
  458. gateway, active_repository, virtual_repository, plc_repository);
  459. MainWindow window(
  460. mode_service,
  461. project_service,
  462. editor_service,
  463. logic_editor_service,
  464. runtime_service,
  465. monitor_service);
  466. window.resize(1200, 760);
  467. window.show();
  468. QApplication::processEvents();
  469. require(mode_service.connectPlc(
  470. {"COM9", 1, 9600, 8, 2, 1, 1000, 2, 200}).succeeded,
  471. "online workspace test must connect the fake PLC gateway");
  472. gateway.completeInitialRead();
  473. QAction *online_action = requiredChild<QAction>(window, "onlineModeAction");
  474. online_action->trigger();
  475. QApplication::processEvents();
  476. QWidget *runtime_tab = requiredChild<QWidget>(window, "runtimeMonitorTab");
  477. QWidget *runtime_hmi = requiredChild<QWidget>(window, "runtimeHmiView");
  478. QWidget *runtime_logic = requiredChild<QWidget>(window, "runtimeLogicView");
  479. QWidget *free_monitor = requiredChild<QWidget>(window, "freeMonitorWidget");
  480. require(mode_service.mode() == ApplicationMode::OnlineRunning,
  481. "completed PLC initial read must allow online running");
  482. require(runtime_tab->isVisible() && runtime_hmi->isVisible()
  483. && free_monitor->isVisible(),
  484. "online running must show HMI and free monitor together");
  485. require(!runtime_logic->isVisible(),
  486. "online running must not show a misleading local ladder runtime trace");
  487. QLineEdit *monitor_address = requiredChild<QLineEdit>(window, "addressEdit");
  488. QPushButton *monitor_add = requiredChild<QPushButton>(window, "addButton");
  489. monitor_address->setText(QStringLiteral("D9"));
  490. monitor_add->click();
  491. require(std::find(
  492. gateway.poll_addresses.begin(),
  493. gateway.poll_addresses.end(),
  494. RegisterAddress{RegisterArea::D, 9}) != gateway.poll_addresses.end(),
  495. "online free monitor addresses must join the active PLC poll set immediately");
  496. }
  497. } // namespace
  498. int main(int argc, char *argv[])
  499. {
  500. // 无窗口平台使 Qt Widgets 测试可在自动化环境稳定运行
  501. qputenv("QT_QPA_PLATFORM", QByteArrayLiteral("offscreen"));
  502. QApplication application(argc, argv);
  503. try
  504. {
  505. testModeActionsControlEditingAvailability();
  506. testPlcConfigurationUsesDialog();
  507. testRepeatedPlcStatusNotificationsAreCoalesced();
  508. testOnlineWorkspaceShowsHmiAndFreeMonitorOnly();
  509. }
  510. catch (const std::exception &error)
  511. {
  512. std::cerr << "main window tests failed: " << error.what() << '\n';
  513. return 1;
  514. }
  515. std::cout << "main window tests passed\n";
  516. return 0;
  517. }