综合平台编程器项目的远程存储
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

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