综合平台编程器项目的远程存储
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

480 行
20 KiB

  1. #include "domain/active_register_repository.h"
  2. #include "domain/project_limits.h"
  3. #include "domain/project_storage.h"
  4. #include "infrastructure/plc_communication_error_classifier.h"
  5. #include "infrastructure/plc_communication_service.h"
  6. #include "support/test_support.h"
  7. #include "infrastructure/plc_register_repository.h"
  8. #include "domain/virtual_register_repository.h"
  9. #include "services/offline_simulation_service.h"
  10. #include "services/plc_communication_gateway.h"
  11. #include "services/plc_discovery_gateway.h"
  12. #include "services/project_service.h"
  13. #include "services/runtime_mode_service.h"
  14. #include "services/logic_editor_service.h"
  15. #include <functional>
  16. #include <iostream>
  17. #include <set>
  18. #include <stdexcept>
  19. #include <tuple>
  20. #include <utility>
  21. namespace {
  22. using TestProjectStorage = TestSupport::InMemoryProjectStorage;
  23. class FakePlcGateway final : public PlcCommunicationGateway
  24. {
  25. public:
  26. PlcCommunicationResult connectDevice(
  27. const PlcSerialConfiguration &configuration) override
  28. {
  29. last_configuration = configuration;
  30. last_error_type = PlcCommunicationError::None;
  31. last_error.clear();
  32. initial_read = false;
  33. connection_state = PlcConnectionState::Connected;
  34. if (state_changed)
  35. {
  36. state_changed();
  37. }
  38. return {true, {}};
  39. }
  40. void disconnectDevice() override
  41. {
  42. ++disconnect_count;
  43. connection_state = PlcConnectionState::Disconnected;
  44. initial_read = false;
  45. if (initial_read_changed)
  46. {
  47. initial_read_changed(false);
  48. }
  49. if (state_changed)
  50. {
  51. state_changed();
  52. }
  53. }
  54. PlcCommunicationResult setPollAddresses(
  55. const std::vector<RegisterAddress> &addresses) override
  56. {
  57. poll_addresses = addresses;
  58. return {true, {}};
  59. }
  60. PlcConnectionState state() const override { return connection_state; }
  61. bool initialReadCompleted() const override { return initial_read; }
  62. PlcCommunicationError lastErrorType() const override { return last_error_type; }
  63. const std::string &lastError() const override { return last_error; }
  64. void setCallbacks(
  65. std::function<void()> state_callback,
  66. std::function<void(bool)> initial_callback,
  67. std::function<void()> cache_callback,
  68. std::function<void()> poll_cycle_callback,
  69. std::function<void(const std::string &)> error_callback) override
  70. {
  71. state_changed = std::move(state_callback);
  72. initial_read_changed = std::move(initial_callback);
  73. cache_updated = std::move(cache_callback);
  74. poll_cycle_completed = std::move(poll_cycle_callback);
  75. error_reported = std::move(error_callback);
  76. }
  77. void completeInitialRead()
  78. {
  79. initial_read = true;
  80. if (initial_read_changed)
  81. {
  82. initial_read_changed(true);
  83. }
  84. }
  85. void failCommunication(
  86. PlcCommunicationError error_type, const std::string &message)
  87. {
  88. initial_read = false;
  89. last_error_type = error_type;
  90. last_error = message;
  91. connection_state = PlcConnectionState::Faulted;
  92. if (initial_read_changed)
  93. {
  94. initial_read_changed(false);
  95. }
  96. if (state_changed)
  97. {
  98. state_changed();
  99. }
  100. if (error_reported)
  101. {
  102. error_reported(last_error);
  103. }
  104. }
  105. PlcConnectionState connection_state = PlcConnectionState::Disconnected;
  106. bool initial_read = false;
  107. int disconnect_count = 0;
  108. PlcCommunicationError last_error_type = PlcCommunicationError::None;
  109. std::string last_error;
  110. PlcSerialConfiguration last_configuration;
  111. std::vector<RegisterAddress> poll_addresses;
  112. std::function<void()> state_changed;
  113. std::function<void(bool)> initial_read_changed;
  114. std::function<void()> cache_updated;
  115. std::function<void()> poll_cycle_completed;
  116. std::function<void(const std::string &)> error_reported;
  117. };
  118. using TestSupport::require;
  119. void testPlcCacheAndWriteForwarding()
  120. {
  121. PlcRegisterRepository repository;
  122. const RegisterAddress m0{RegisterArea::M, 0};
  123. const RegisterAddress d0{RegisterArea::D, 0};
  124. require(repository.readBit(m0).error == RegisterError::Unavailable,
  125. "uninitialized PLC bit cache must be unavailable");
  126. require(repository.readWord(d0).error == RegisterError::Unavailable,
  127. "uninitialized PLC word cache must be unavailable");
  128. repository.updateBit(0, true);
  129. repository.updateWord(0, -123);
  130. require(repository.readBit(m0).succeeded && repository.readBit(m0).value,
  131. "valid PLC bit cache must be readable");
  132. require(repository.readWord(d0).succeeded
  133. && repository.readWord(d0).value == -123,
  134. "valid PLC word cache must preserve signed values");
  135. RegisterAddress written_address{RegisterArea::M, 1};
  136. bool written_bit = false;
  137. std::int16_t written_word = 0;
  138. repository.setWriteHandlers(
  139. [&](const RegisterAddress &address, bool value)
  140. {
  141. written_address = address;
  142. written_bit = value;
  143. return RegisterWriteResult{true, RegisterError::None};
  144. },
  145. [&](const RegisterAddress &address, std::int16_t value)
  146. {
  147. written_address = address;
  148. written_word = value;
  149. return RegisterWriteResult{true, RegisterError::None};
  150. });
  151. require(repository.writeBit(m0, false).succeeded
  152. && written_address == m0 && !written_bit,
  153. "PLC bit writes must be forwarded without changing the cache");
  154. require(repository.writeWord(d0, 456).succeeded
  155. && written_address == d0 && written_word == 456,
  156. "PLC word writes must be forwarded without changing the cache");
  157. repository.invalidate();
  158. require(!repository.hasAnyValidValue(),
  159. "disconnecting must invalidate all PLC cache validity flags");
  160. }
  161. void testRuntimeRepositorySwitchingAndDisconnect()
  162. {
  163. TestProjectStorage storage;
  164. ProjectService project_service(storage);
  165. HmiPage page;
  166. page.id = "main-page";
  167. page.name = "Main";
  168. HmiControl indicator;
  169. indicator.id = "run-state";
  170. indicator.type = HmiControlType::Indicator;
  171. indicator.bounds = {0, 0, 80, 40};
  172. indicator.text = "Run";
  173. indicator.binding = RegisterAddress{RegisterArea::M, 5};
  174. page.controls.push_back(indicator);
  175. project_service.editProject().initialHmiPageId = page.id;
  176. project_service.editProject().hmiPages.push_back(page);
  177. VirtualRegisterRepository virtual_repository;
  178. PlcRegisterRepository plc_repository;
  179. ActiveRegisterRepository active_repository(virtual_repository);
  180. OfflineSimulationService simulation_service(virtual_repository);
  181. OnlineLogicMonitorService online_monitor_service(plc_repository);
  182. LogicEditorService logic_editor_service(project_service);
  183. FakePlcGateway gateway;
  184. RuntimeModeService service(
  185. project_service,
  186. logic_editor_service,
  187. simulation_service,
  188. online_monitor_service);
  189. service.configurePlc(
  190. gateway, active_repository, virtual_repository, plc_repository);
  191. const PlcCommunicationResult connected = service.connectPlc(
  192. {"COM9", 2, 19200, 8, 2, 1, 1000, 2, 200});
  193. require(connected.succeeded && gateway.poll_addresses.size() == 1U,
  194. "PLC connection must receive the project address poll set");
  195. service.setMonitorAddresses({
  196. RegisterAddress{RegisterArea::M, 5},
  197. RegisterAddress{RegisterArea::D, 8}});
  198. require(gateway.poll_addresses.size() == 2U
  199. && gateway.poll_addresses.front()
  200. == RegisterAddress{RegisterArea::M, 5}
  201. && gateway.poll_addresses.back()
  202. == RegisterAddress{RegisterArea::D, 8},
  203. "monitor addresses must merge with and deduplicate project poll addresses");
  204. require(service.enterOnlineRunning().error
  205. == ModeTransitionError::InitialPlcReadRequired,
  206. "online mode must wait for the first valid PLC read");
  207. plc_repository.updateBit(5, true);
  208. gateway.completeInitialRead();
  209. require(service.enterOnlineRunning().succeeded,
  210. "online mode must start after the first valid PLC read");
  211. require(active_repository.readBit({RegisterArea::M, 5}).succeeded
  212. && active_repository.readBit({RegisterArea::M, 5}).value,
  213. "online mode must expose the PLC cache through the active repository");
  214. gateway.disconnectDevice();
  215. require(service.mode() == ApplicationMode::Editing,
  216. "an online disconnect must return the application to editing mode");
  217. require(service.onlineLogicMonitorService().state()
  218. == OnlineLogicMonitorState::Stopped,
  219. "an online disconnect must stop the local read-only trace executor");
  220. require(!service.initialPlcReadCompleted(),
  221. "an online disconnect must clear the initial read flag");
  222. require(active_repository.readBit({RegisterArea::M, 5}).succeeded
  223. && !active_repository.readBit({RegisterArea::M, 5}).value,
  224. "editing after disconnect must switch back to the virtual repository");
  225. }
  226. void testRuntimeFaultRevokesOnlineReadinessAndAllowsReconnect()
  227. {
  228. TestProjectStorage storage;
  229. ProjectService project_service(storage);
  230. VirtualRegisterRepository virtual_repository;
  231. PlcRegisterRepository plc_repository;
  232. ActiveRegisterRepository active_repository(virtual_repository);
  233. OfflineSimulationService simulation_service(virtual_repository);
  234. OnlineLogicMonitorService online_monitor_service(plc_repository);
  235. LogicEditorService logic_editor_service(project_service);
  236. FakePlcGateway gateway;
  237. RuntimeModeService service(
  238. project_service,
  239. logic_editor_service,
  240. simulation_service,
  241. online_monitor_service);
  242. service.configurePlc(
  243. gateway, active_repository, virtual_repository, plc_repository);
  244. require(service.connectPlc(
  245. {"COM9", 1, 9600, 8, 2, 1, 1000, 2, 200}).succeeded,
  246. "PLC connection must start before testing a communication fault");
  247. gateway.completeInitialRead();
  248. require(service.enterOnlineRunning().succeeded,
  249. "completed initial read must allow online running before a fault");
  250. gateway.failCommunication(
  251. PlcCommunicationError::CommunicationTimeout,
  252. "PLC communication timed out while the serial port remained open");
  253. require(service.mode() == ApplicationMode::Editing,
  254. "a PLC communication fault must return online running to editing");
  255. require(service.onlineLogicMonitorService().state()
  256. == OnlineLogicMonitorState::Stopped,
  257. "a PLC communication fault must stop the local trace executor");
  258. require(!service.initialPlcReadCompleted(),
  259. "a PLC communication fault must revoke initial read readiness");
  260. require(service.enterOnlineRunning().error
  261. == ModeTransitionError::InitialPlcReadRequired,
  262. "faulted PLC state must not reuse readiness from the previous connection");
  263. const int disconnect_count = gateway.disconnect_count;
  264. require(service.connectPlc(
  265. {"COM9", 1, 9600, 8, 2, 1, 1000, 2, 200}).succeeded,
  266. "faulted PLC state must support direct reconnect");
  267. require(gateway.disconnect_count == disconnect_count + 1,
  268. "reconnecting from a fault must clean the previous serial session first");
  269. }
  270. void testPlcCommunicationErrorClassification()
  271. {
  272. PlcCommunicationErrorContext context;
  273. context.portName = QStringLiteral("COM3");
  274. PlcCommunicationFailure failure = classifyPlcCommunicationError(
  275. QModbusDevice::ConnectionError, context);
  276. require(failure.type == PlcCommunicationError::SerialPortOpenFailed
  277. && failure.message.contains(QStringLiteral("未能打开")),
  278. "connection failure before opening the port must be classified explicitly");
  279. context.serialSessionOpened = true;
  280. failure = classifyPlcCommunicationError(QModbusDevice::TimeoutError, context);
  281. require(failure.type == PlcCommunicationError::PlcNotResponding
  282. && failure.message.contains(QStringLiteral("PLC 未响应")),
  283. "initial timeout with an open serial port must report a non-responsive PLC");
  284. context.receivedValidResponse = true;
  285. failure = classifyPlcCommunicationError(QModbusDevice::TimeoutError, context);
  286. require(failure.type == PlcCommunicationError::CommunicationTimeout
  287. && failure.message.contains(QStringLiteral("仍处于打开状态")),
  288. "timeout after valid traffic must report an open local serial session");
  289. failure = classifyPlcCommunicationError(QModbusDevice::ConnectionError, context);
  290. require(failure.type == PlcCommunicationError::SerialConnectionLost
  291. && failure.message.contains(QStringLiteral("连接已中断")),
  292. "connection errors after opening the port must report a lost serial link");
  293. failure = classifyPlcCommunicationError(QModbusDevice::ProtocolError, context);
  294. require(failure.type == PlcCommunicationError::ProtocolError
  295. && failure.message.contains(QStringLiteral("Modbus 协议异常")),
  296. "protocol errors must remain distinct from timeouts and disconnections");
  297. }
  298. void testPlcConfigurationBoundaries()
  299. {
  300. PlcSerialConfiguration configuration;
  301. configuration.portName = "COM3";
  302. require(validatePlcSerialConfiguration(configuration).succeeded,
  303. "the standard COM3 9600 8E1 configuration must be accepted");
  304. configuration.serverAddress = ProjectLimits::kMaximumPlcServerAddress;
  305. require(validatePlcSerialConfiguration(configuration).succeeded,
  306. "PLC station 247 must be accepted");
  307. configuration.serverAddress = ProjectLimits::kMaximumPlcServerAddress + 1;
  308. require(!validatePlcSerialConfiguration(configuration).succeeded,
  309. "PLC station 248 must be rejected");
  310. configuration.serverAddress = 1;
  311. configuration.retries = ProjectLimits::kMaximumRetries;
  312. require(validatePlcSerialConfiguration(configuration).succeeded,
  313. "five retries must be accepted");
  314. configuration.retries = ProjectLimits::kMaximumRetries + 1;
  315. require(!validatePlcSerialConfiguration(configuration).succeeded,
  316. "six retries must be rejected");
  317. configuration.retries = 0;
  318. configuration.responseTimeoutMs = ProjectLimits::kMinimumResponseTimeoutMs - 1;
  319. require(!validatePlcSerialConfiguration(configuration).succeeded,
  320. "a response timeout below 100 ms must be rejected");
  321. configuration.responseTimeoutMs = ProjectLimits::kMinimumResponseTimeoutMs;
  322. require(validatePlcSerialConfiguration(configuration).succeeded,
  323. "a response timeout of 100 ms must be accepted");
  324. }
  325. void testPlcDiscoveryCandidatePriorityAndCoverage()
  326. {
  327. PlcSerialConfiguration preferred;
  328. preferred.portName = "COM3";
  329. preferred.serverAddress = 17;
  330. preferred.baudRate = 38400;
  331. preferred.dataBits = 7;
  332. preferred.parity = 3;
  333. preferred.stopBits = 2;
  334. preferred.responseTimeoutMs = 1500;
  335. preferred.retries = 4;
  336. preferred.pollIntervalMs = 350;
  337. const std::vector<PlcSerialConfiguration> candidates =
  338. buildPlcDiscoveryCandidates(
  339. preferred, {"COM1", "COM2", "COM3", "COM2", ""});
  340. require(candidates.size() == 180U,
  341. "discovery must cover 60 serial settings on every unique available port");
  342. require(candidates.front().portName == "COM3"
  343. && candidates.front().serverAddress == 17
  344. && candidates.front().baudRate == 38400
  345. && candidates.front().dataBits == 7
  346. && candidates.front().parity == 3
  347. && candidates.front().stopBits == 2,
  348. "discovery must try the complete current configuration first");
  349. require(candidates.at(1).portName == "COM1"
  350. && candidates.at(2).portName == "COM2",
  351. "the preferred port must be first without dropping other ports");
  352. std::set<std::tuple<std::string, int, int, int, int>> unique_candidates;
  353. bool contains_standard_8e1 = false;
  354. bool contains_full_supported_edge = false;
  355. for (const PlcSerialConfiguration &candidate : candidates)
  356. {
  357. require(candidate.serverAddress == preferred.serverAddress
  358. && candidate.responseTimeoutMs == preferred.responseTimeoutMs
  359. && candidate.retries == preferred.retries
  360. && candidate.pollIntervalMs == preferred.pollIntervalMs,
  361. "discovery must preserve the selected station and normal timing settings");
  362. unique_candidates.emplace(
  363. candidate.portName,
  364. candidate.baudRate,
  365. candidate.dataBits,
  366. candidate.parity,
  367. candidate.stopBits);
  368. contains_standard_8e1 = contains_standard_8e1
  369. || (candidate.portName == "COM2"
  370. && candidate.baudRate == 9600
  371. && candidate.dataBits == 8
  372. && candidate.parity == 2
  373. && candidate.stopBits == 1);
  374. contains_full_supported_edge = contains_full_supported_edge
  375. || (candidate.portName == "COM1"
  376. && candidate.baudRate == 115200
  377. && candidate.dataBits == 7
  378. && candidate.parity == 0
  379. && candidate.stopBits == 2);
  380. }
  381. require(unique_candidates.size() == candidates.size(),
  382. "discovery candidates must not contain duplicate serial settings");
  383. require(contains_standard_8e1 && contains_full_supported_edge,
  384. "discovery must cover common settings and every supported boundary");
  385. require(buildPlcDiscoveryCandidates(preferred, {}).empty(),
  386. "discovery must stop immediately when no serial port is available");
  387. }
  388. void testPlcPollQuantityBoundaries()
  389. {
  390. PlcRegisterRepository repository;
  391. PlcCommunicationService service(repository);
  392. std::vector<RegisterAddress> too_many_addresses;
  393. for (int index = 0; index <= RegisterAddress::kMaximumIndex; ++index)
  394. {
  395. too_many_addresses.push_back({RegisterArea::M, index});
  396. }
  397. too_many_addresses.push_back({RegisterArea::D, 0});
  398. require(!service.setPollAddresses(too_many_addresses).succeeded,
  399. "more than the configured poll address limit must be rejected");
  400. std::vector<RegisterAddress> too_many_blocks;
  401. for (std::size_t index = 0;
  402. index < ProjectLimits::kMaximumPollBlocks + 1U;
  403. ++index)
  404. {
  405. too_many_blocks.push_back({RegisterArea::M, static_cast<int>(index * 2U)});
  406. }
  407. require(!service.setPollAddresses(too_many_blocks).succeeded,
  408. "more than the configured Modbus read block limit must be rejected");
  409. std::vector<RegisterAddress> maximum_contiguous_block;
  410. for (int index = 0; index < ProjectLimits::kMaximumModbusReadCount; ++index)
  411. {
  412. maximum_contiguous_block.push_back({RegisterArea::M, index});
  413. }
  414. require(service.setPollAddresses(maximum_contiguous_block).succeeded,
  415. "a contiguous Modbus read block of 120 values must be accepted");
  416. }
  417. } // namespace
  418. int main()
  419. {
  420. try
  421. {
  422. testPlcCacheAndWriteForwarding();
  423. testRuntimeRepositorySwitchingAndDisconnect();
  424. testRuntimeFaultRevokesOnlineReadinessAndAllowsReconnect();
  425. testPlcCommunicationErrorClassification();
  426. testPlcConfigurationBoundaries();
  427. testPlcDiscoveryCandidatePriorityAndCoverage();
  428. testPlcPollQuantityBoundaries();
  429. }
  430. catch (const std::exception &error)
  431. {
  432. std::cerr << "PLC runtime tests failed: " << error.what() << '\n';
  433. return 1;
  434. }
  435. std::cout << "PLC runtime tests passed\n";
  436. return 0;
  437. }