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.

935 lines
49 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock Leaks that grew without bound: - Dead module connections were never removed (half-open TCP after a module power loss / network drop): every one kept 3 threads, 8 MB of socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s; la_mojo sends a status about every second), and accepted sockets get TCP keepalive (30 s idle, 3 probes of 10 s). - The client socket was only closed on an I/O error: a handler removed for any other reason (module disabled / not registered, idle) leaked its descriptor until accept() failed with EMFILE - which ended the accept thread for good. ~serverPort now shuts down and closes it; transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED, EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is always a disconnect, whatever errno holds. - servaSessionManager::reopenSession stored the reopened (expired) session in the per-track map, overwriting the track's ACTIVE session: its data and open report.db leaked and it was never closed in MySQL. Reopened sessions are now kept outside the map and released by the caller (addVideo, getSessionBase). - servaVideoComposer leaked its session data, an open SQLite connection and both video queues on every composition; servaKernel leaked a composer whose compose() failed, never initialised / released the automatic composer (it ran at most once) and leaked the media info of every encoded video (processVideoFile success path). Crashes / corruption: - vector erase() with the old iterator reused (netServer client cleanup, encoder / composer pools, 4 ModBus action loops). - transportSocket::_close wrote the stop byte into the read end of the pipe (threads only stopped at the 5 s select timeout, blocking the accept thread on every disconnect) and left closed pipe numbers set (a second _close could write into another connection's socket). - Session map used without the lock from RPC, kernel and ModBus threads: now a recursive mutex held for each public operation. - Freeze on the first MySQL error with DB logging enabled: Query() logs while holding the non-recursive DB mutex and the log service wrote synchronously into the DB (same-thread and two-thread deadlock). The DB log service now queues lines (max 1000) and writes them with MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect retries per query are bounded (3) instead of looping forever while holding the mutex. The log line parser also skips the UTC offset. - basicMutex::try_lock returned true when the lock was NOT taken: an uncontended try_lock took the mutex and the caller never released it (basicEngine, serial transport, ...). - Kernel restart (web commands): the ModBus singleton was deleted but not reset (next getInstance returned freed memory), the remote client kept the deleted kernel and refused to start again, and EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving component still used. Now fixed / the DB object is kept. - Life monitoring overflowed module_id[4] for platforms with > 4 modules; registerServA overflowed a 120-byte stack buffer, closed a popen() stream with fclose and leaked the config; 9 config strings in servaBackend were allocated one byte short; video chunk length is now checked against the packet; "eased" events copied every field from itself (all 0); networkServer freed libconfig's host string. Minor: ModBus action list / sessions freed at shutdown, session-start event payload freed if the event cannot be created, the per-second "No History Auto Delete!" log line moved to DEBUG_EXTRA. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
1 hour ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock Leaks that grew without bound: - Dead module connections were never removed (half-open TCP after a module power loss / network drop): every one kept 3 threads, 8 MB of socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s; la_mojo sends a status about every second), and accepted sockets get TCP keepalive (30 s idle, 3 probes of 10 s). - The client socket was only closed on an I/O error: a handler removed for any other reason (module disabled / not registered, idle) leaked its descriptor until accept() failed with EMFILE - which ended the accept thread for good. ~serverPort now shuts down and closes it; transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED, EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is always a disconnect, whatever errno holds. - servaSessionManager::reopenSession stored the reopened (expired) session in the per-track map, overwriting the track's ACTIVE session: its data and open report.db leaked and it was never closed in MySQL. Reopened sessions are now kept outside the map and released by the caller (addVideo, getSessionBase). - servaVideoComposer leaked its session data, an open SQLite connection and both video queues on every composition; servaKernel leaked a composer whose compose() failed, never initialised / released the automatic composer (it ran at most once) and leaked the media info of every encoded video (processVideoFile success path). Crashes / corruption: - vector erase() with the old iterator reused (netServer client cleanup, encoder / composer pools, 4 ModBus action loops). - transportSocket::_close wrote the stop byte into the read end of the pipe (threads only stopped at the 5 s select timeout, blocking the accept thread on every disconnect) and left closed pipe numbers set (a second _close could write into another connection's socket). - Session map used without the lock from RPC, kernel and ModBus threads: now a recursive mutex held for each public operation. - Freeze on the first MySQL error with DB logging enabled: Query() logs while holding the non-recursive DB mutex and the log service wrote synchronously into the DB (same-thread and two-thread deadlock). The DB log service now queues lines (max 1000) and writes them with MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect retries per query are bounded (3) instead of looping forever while holding the mutex. The log line parser also skips the UTC offset. - basicMutex::try_lock returned true when the lock was NOT taken: an uncontended try_lock took the mutex and the caller never released it (basicEngine, serial transport, ...). - Kernel restart (web commands): the ModBus singleton was deleted but not reset (next getInstance returned freed memory), the remote client kept the deleted kernel and refused to start again, and EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving component still used. Now fixed / the DB object is kept. - Life monitoring overflowed module_id[4] for platforms with > 4 modules; registerServA overflowed a 120-byte stack buffer, closed a popen() stream with fclose and leaked the config; 9 config strings in servaBackend were allocated one byte short; video chunk length is now checked against the packet; "eased" events copied every field from itself (all 0); networkServer freed libconfig's host string. Minor: ModBus action list / sessions freed at shutdown, session-start event payload freed if the event cannot be created, the per-second "No History Auto Delete!" log line moved to DEBUG_EXTRA. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
1 hour ago
​
​
​
​
​
​
​
​
12 months ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock Leaks that grew without bound: - Dead module connections were never removed (half-open TCP after a module power loss / network drop): every one kept 3 threads, 8 MB of socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s; la_mojo sends a status about every second), and accepted sockets get TCP keepalive (30 s idle, 3 probes of 10 s). - The client socket was only closed on an I/O error: a handler removed for any other reason (module disabled / not registered, idle) leaked its descriptor until accept() failed with EMFILE - which ended the accept thread for good. ~serverPort now shuts down and closes it; transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED, EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is always a disconnect, whatever errno holds. - servaSessionManager::reopenSession stored the reopened (expired) session in the per-track map, overwriting the track's ACTIVE session: its data and open report.db leaked and it was never closed in MySQL. Reopened sessions are now kept outside the map and released by the caller (addVideo, getSessionBase). - servaVideoComposer leaked its session data, an open SQLite connection and both video queues on every composition; servaKernel leaked a composer whose compose() failed, never initialised / released the automatic composer (it ran at most once) and leaked the media info of every encoded video (processVideoFile success path). Crashes / corruption: - vector erase() with the old iterator reused (netServer client cleanup, encoder / composer pools, 4 ModBus action loops). - transportSocket::_close wrote the stop byte into the read end of the pipe (threads only stopped at the 5 s select timeout, blocking the accept thread on every disconnect) and left closed pipe numbers set (a second _close could write into another connection's socket). - Session map used without the lock from RPC, kernel and ModBus threads: now a recursive mutex held for each public operation. - Freeze on the first MySQL error with DB logging enabled: Query() logs while holding the non-recursive DB mutex and the log service wrote synchronously into the DB (same-thread and two-thread deadlock). The DB log service now queues lines (max 1000) and writes them with MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect retries per query are bounded (3) instead of looping forever while holding the mutex. The log line parser also skips the UTC offset. - basicMutex::try_lock returned true when the lock was NOT taken: an uncontended try_lock took the mutex and the caller never released it (basicEngine, serial transport, ...). - Kernel restart (web commands): the ModBus singleton was deleted but not reset (next getInstance returned freed memory), the remote client kept the deleted kernel and refused to start again, and EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving component still used. Now fixed / the DB object is kept. - Life monitoring overflowed module_id[4] for platforms with > 4 modules; registerServA overflowed a 120-byte stack buffer, closed a popen() stream with fclose and leaked the config; 9 config strings in servaBackend were allocated one byte short; video chunk length is now checked against the packet; "eased" events copied every field from itself (all 0); networkServer freed libconfig's host string. Minor: ModBus action list / sessions freed at shutdown, session-start event payload freed if the event cannot be created, the per-second "No History Auto Delete!" log line moved to DEBUG_EXTRA. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
1 hour ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 weeks ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock Leaks that grew without bound: - Dead module connections were never removed (half-open TCP after a module power loss / network drop): every one kept 3 threads, 8 MB of socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s; la_mojo sends a status about every second), and accepted sockets get TCP keepalive (30 s idle, 3 probes of 10 s). - The client socket was only closed on an I/O error: a handler removed for any other reason (module disabled / not registered, idle) leaked its descriptor until accept() failed with EMFILE - which ended the accept thread for good. ~serverPort now shuts down and closes it; transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED, EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is always a disconnect, whatever errno holds. - servaSessionManager::reopenSession stored the reopened (expired) session in the per-track map, overwriting the track's ACTIVE session: its data and open report.db leaked and it was never closed in MySQL. Reopened sessions are now kept outside the map and released by the caller (addVideo, getSessionBase). - servaVideoComposer leaked its session data, an open SQLite connection and both video queues on every composition; servaKernel leaked a composer whose compose() failed, never initialised / released the automatic composer (it ran at most once) and leaked the media info of every encoded video (processVideoFile success path). Crashes / corruption: - vector erase() with the old iterator reused (netServer client cleanup, encoder / composer pools, 4 ModBus action loops). - transportSocket::_close wrote the stop byte into the read end of the pipe (threads only stopped at the 5 s select timeout, blocking the accept thread on every disconnect) and left closed pipe numbers set (a second _close could write into another connection's socket). - Session map used without the lock from RPC, kernel and ModBus threads: now a recursive mutex held for each public operation. - Freeze on the first MySQL error with DB logging enabled: Query() logs while holding the non-recursive DB mutex and the log service wrote synchronously into the DB (same-thread and two-thread deadlock). The DB log service now queues lines (max 1000) and writes them with MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect retries per query are bounded (3) instead of looping forever while holding the mutex. The log line parser also skips the UTC offset. - basicMutex::try_lock returned true when the lock was NOT taken: an uncontended try_lock took the mutex and the caller never released it (basicEngine, serial transport, ...). - Kernel restart (web commands): the ModBus singleton was deleted but not reset (next getInstance returned freed memory), the remote client kept the deleted kernel and refused to start again, and EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving component still used. Now fixed / the DB object is kept. - Life monitoring overflowed module_id[4] for platforms with > 4 modules; registerServA overflowed a 120-byte stack buffer, closed a popen() stream with fclose and leaked the config; 9 config strings in servaBackend were allocated one byte short; video chunk length is now checked against the packet; "eased" events copied every field from itself (all 0); networkServer freed libconfig's host string. Minor: ModBus action list / sessions freed at shutdown, session-start event payload freed if the event cannot be created, the per-second "No History Auto Delete!" log line moved to DEBUG_EXTRA. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
1 hour ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 weeks ago
4 weeks ago
​
​
​
​
​
​
​
​
​
​
​
​
​
la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock Leaks that grew without bound: - Dead module connections were never removed (half-open TCP after a module power loss / network drop): every one kept 3 threads, 8 MB of socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s; la_mojo sends a status about every second), and accepted sockets get TCP keepalive (30 s idle, 3 probes of 10 s). - The client socket was only closed on an I/O error: a handler removed for any other reason (module disabled / not registered, idle) leaked its descriptor until accept() failed with EMFILE - which ended the accept thread for good. ~serverPort now shuts down and closes it; transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED, EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is always a disconnect, whatever errno holds. - servaSessionManager::reopenSession stored the reopened (expired) session in the per-track map, overwriting the track's ACTIVE session: its data and open report.db leaked and it was never closed in MySQL. Reopened sessions are now kept outside the map and released by the caller (addVideo, getSessionBase). - servaVideoComposer leaked its session data, an open SQLite connection and both video queues on every composition; servaKernel leaked a composer whose compose() failed, never initialised / released the automatic composer (it ran at most once) and leaked the media info of every encoded video (processVideoFile success path). Crashes / corruption: - vector erase() with the old iterator reused (netServer client cleanup, encoder / composer pools, 4 ModBus action loops). - transportSocket::_close wrote the stop byte into the read end of the pipe (threads only stopped at the 5 s select timeout, blocking the accept thread on every disconnect) and left closed pipe numbers set (a second _close could write into another connection's socket). - Session map used without the lock from RPC, kernel and ModBus threads: now a recursive mutex held for each public operation. - Freeze on the first MySQL error with DB logging enabled: Query() logs while holding the non-recursive DB mutex and the log service wrote synchronously into the DB (same-thread and two-thread deadlock). The DB log service now queues lines (max 1000) and writes them with MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect retries per query are bounded (3) instead of looping forever while holding the mutex. The log line parser also skips the UTC offset. - basicMutex::try_lock returned true when the lock was NOT taken: an uncontended try_lock took the mutex and the caller never released it (basicEngine, serial transport, ...). - Kernel restart (web commands): the ModBus singleton was deleted but not reset (next getInstance returned freed memory), the remote client kept the deleted kernel and refused to start again, and EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving component still used. Now fixed / the DB object is kept. - Life monitoring overflowed module_id[4] for platforms with > 4 modules; registerServA overflowed a 120-byte stack buffer, closed a popen() stream with fclose and leaked the config; 9 config strings in servaBackend were allocated one byte short; video chunk length is now checked against the packet; "eased" events copied every field from itself (all 0); networkServer freed libconfig's host string. Minor: ModBus action list / sessions freed at shutdown, session-start event payload freed if the event cannot be created, the per-second "No History Auto Delete!" log line moved to DEBUG_EXTRA. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
1 hour ago
​
​
​
​
​
​
​
​
​
​
​
  1. #include "servaModBusManager.h"
  2. #include "servaKernel.h"
  3. #define LOG( X ) m_pLog->Log( "MODBUS", this, X )
  4. #ifdef DEBUG
  5. #define LOG_ERROR( X ) {\
  6. char _tBfrErrMSG2w34[256];\
  7. sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  8. m_pLog->Log( "MODBUS", this, _LOG_ERROR, _tBfrErrMSG2w34 );\
  9. }
  10. #else
  11. #define LOG_ERROR( X ) m_pLog->Log( "MODBUS", this, _LOG_ERROR, X );
  12. #endif
  13. servaModBusManager *servaModBusManager::_instance = NULL;
  14. servaModBusManager *servaModBusManager::getInstance(){
  15. if ( _instance == NULL ) {
  16. _instance = new servaModBusManager();
  17. };
  18. return _instance;
  19. };
  20. servaModBusManager::servaModBusManager():basicThread(),basicValidatable(){
  21. m_bStage = MBUS_STAGE_INIT;
  22. m_pDBC = NULL;
  23. m_pLog = basicLogCollection::getInstance();
  24. m_pMaster = servaKernel::getInstance();
  25. if ( m_pMaster == NULL ) return;
  26. m_pDBC = m_pMaster->getDBC();
  27. memset( &m_sManagerData, 0, sizeof( MODBUS_MANAGER_DATA ));
  28. };
  29. servaModBusManager::~servaModBusManager(){
  30. waitThreadEnd( true );
  31. // The kernel deletes this singleton on restart: the next getInstance() must create a new one
  32. // (it returned the deleted object before)
  33. if ( _instance == this ) _instance = NULL;
  34. m_mProtector.lock();
  35. for ( V_MODBUS_ACION_ITEMS::iterator idx = m_vActioItems.begin(); idx != m_vActioItems.end(); idx++ ) free( *idx );
  36. m_vActioItems.clear();
  37. m_mProtector.unlock();
  38. if (m_vRtuUnits.size()) {
  39. for( V_MODBUS_RTU_INFO::iterator idx=m_vRtuUnits.begin(); idx != m_vRtuUnits.end(); idx++ ) {
  40. free( *idx );
  41. };
  42. m_vRtuUnits.clear();
  43. };
  44. };
  45. bool servaModBusManager::create(){
  46. if( m_pMaster == NULL ) return false;
  47. if( m_pDBC == NULL ) return false;
  48. MODBUS_MANAGER_DATA * tData = m_pDBC->getModBusManagerData();
  49. if ( tData ) {
  50. memcpy( &m_sManagerData, tData, sizeof( MODBUS_MANAGER_DATA ) );
  51. free( tData );
  52. };
  53. m_bStage = MBUS_STAGE_INIT;
  54. return init();
  55. };
  56. int servaModBusManager::modbus_get_rtu( CSTR ip, uint16_t port, uint8_t addr, uint8_t &status ){
  57. uint8_t buf[16];
  58. modbus_t * ctx; // Modbus context pointer
  59. int rc; // Return code for error checking
  60. // Create a new Modbus TCP context for a slave device
  61. ctx = modbus_new_tcp( ip, port );
  62. if (ctx == NULL) {
  63. #ifdef DEBUG_EXTRA
  64. LOG( "Unable to create the Modbus context" );
  65. #endif
  66. return -1;
  67. };
  68. // Connect to the Modbus TCP slave device
  69. rc = modbus_connect(ctx);
  70. if (rc == -1) {
  71. #ifdef DEBUG_EXTRA
  72. char tB[256];
  73. sprintf(tB, "Connection failed: %s", modbus_strerror(errno));
  74. LOG( tB );
  75. #endif
  76. modbus_free(ctx);
  77. return -1;
  78. };
  79. rc = modbus_read_bits(ctx, addr, 8, buf ); //0x10
  80. if( rc == -1 ) {
  81. #ifdef DEBUG_EXTRA
  82. char tB[256];
  83. sprintf(tB, "Write register failed: %s", modbus_strerror(errno));
  84. LOG( tB );
  85. #endif
  86. } else {
  87. status = modbus_get_byte_from_bits( buf, 0, 8 );
  88. };
  89. // Close the Modbus TCP connection and free the context
  90. modbus_close(ctx);
  91. modbus_free(ctx);
  92. return rc;
  93. };
  94. int servaModBusManager::modbus_set_rtu( CSTR ip, uint16_t port, uint8_t addr, uint8_t data ){
  95. uint8_t bits[8];
  96. modbus_t * ctx; // Modbus context pointer
  97. int rc; // Return code for error checking
  98. // Create a new Modbus TCP context for a slave device
  99. ctx = modbus_new_tcp( ip, port );
  100. if (ctx == NULL) {
  101. #ifdef DEBUG_EXTRA
  102. LOG( "Unable to create the Modbus context");
  103. #endif
  104. return -1;
  105. };
  106. // Connect to the Modbus TCP slave device
  107. rc = modbus_connect(ctx);
  108. if (rc == -1) {
  109. #ifdef DEBUG_EXTRA
  110. char tB[256];
  111. sprintf(tB, "Connection failed: %s", modbus_strerror(errno));
  112. LOG( tB );
  113. #endif
  114. modbus_free(ctx);
  115. return -1;
  116. };
  117. modbus_set_bits_from_byte( bits, 0, data );
  118. rc = modbus_write_bits(ctx, addr, 8, bits ); //0x10
  119. if (rc == -1) {
  120. #ifdef DEBUG_EXTRA
  121. char tB[256];
  122. sprintf(tB, "Write register failed: %s", modbus_strerror(errno));
  123. LOG( tB );
  124. #endif
  125. };
  126. // Close the Modbus TCP connection and free the context
  127. modbus_close(ctx);
  128. modbus_free(ctx);
  129. return rc;
  130. };
  131. int servaModBusManager::modbus_set_rtu_bit( CSTR ip, uint16_t port, uint8_t addr, uint8_t bit ){
  132. modbus_t * ctx; // Modbus context pointer
  133. int rc; // Return code for error checking
  134. // Create a new Modbus TCP context for a slave device
  135. ctx = modbus_new_tcp( ip, port );
  136. if (ctx == NULL) {
  137. #ifdef DEBUG_EXTRA
  138. LOG( "Unable to create the Modbus context");
  139. #endif
  140. return -1;
  141. };
  142. // Connect to the Modbus TCP slave device
  143. rc = modbus_connect(ctx);
  144. if (rc == -1) {
  145. #ifdef DEBUG_EXTRA
  146. char tB[256];
  147. sprintf(tB, "Connection failed: %s", modbus_strerror(errno));
  148. LOG( tB );
  149. #endif
  150. modbus_free(ctx);
  151. return -1;
  152. };
  153. rc = modbus_write_bit(ctx, addr, bit ); //0x10
  154. if (rc == -1) {
  155. #ifdef DEBUG_EXTRA
  156. char tB[256];
  157. sprintf(tB, "Write register failed: %s", modbus_strerror(errno));
  158. LOG( tB );
  159. #endif
  160. };
  161. // Close the Modbus TCP connection and free the context
  162. modbus_close(ctx);
  163. modbus_free(ctx);
  164. return rc;
  165. };
  166. void servaModBusManager::m_fThreadProc( void ){
  167. m_bThreadStatus = TH_WORKING;
  168. uint32_t oss = time(NULL);
  169. while ( m_bThreadStatus < TH_ENDED ) {
  170. uint32_t css = time(NULL);
  171. switch (m_bStage) {
  172. case MBUS_STAGE_INIT:{
  173. #ifdef DEBUG
  174. LOG("Clear Loadded ModBus Modules");
  175. #endif
  176. if (m_vRtuUnits.size()) {
  177. for( V_MODBUS_RTU_INFO::iterator idx=m_vRtuUnits.begin(); idx != m_vRtuUnits.end(); idx++ ) {
  178. free( *idx );
  179. };
  180. m_vRtuUnits.clear();
  181. };
  182. #ifdef DEBUG
  183. LOG("Load Enabled ModBus Modules");
  184. #endif
  185. DBC_UINT64_LIST *tList = m_pDBC->listModBusRTUs( 0, 'E' );
  186. if ( tList ) {
  187. if ( tList->size() ) {
  188. for ( DBC_UINT64_LIST::iterator idx = tList->begin(); idx != tList->end(); idx++ ) {
  189. MODBUS_RTU_INFO *tData = m_pDBC->getModBusRTU( *idx );
  190. if ( tData ) {
  191. m_vRtuUnits.push_back( tData );
  192. };
  193. };
  194. };
  195. delete(tList);
  196. #ifdef DEBUG
  197. LOG("Load ModBus Modules Done");
  198. #endif
  199. } else LOG("No ModBus Modules Defined");
  200. m_bStage = MBUS_STAGE_SYNC;
  201. break;
  202. };
  203. case MBUS_STAGE_SYNC:{
  204. #ifdef DEBUG_EXTRA
  205. LOG("Sync ModBus Modules");
  206. #endif
  207. if( m_vRtuUnits.size() ){
  208. for( V_MODBUS_RTU_INFO::iterator idx = m_vRtuUnits.begin(); idx!= m_vRtuUnits.end(); idx++ ){
  209. int rv = modbus_get_rtu((*idx)->ip, (*idx)->port, (*idx)->output_base_addr, (*idx)->c_OutBits );
  210. if ( rv != -1 ) {
  211. rv = modbus_get_rtu((*idx)->ip, (*idx)->port, (*idx)->input_base_addr, (*idx)->c_InBits );
  212. if ( rv != -1 ) {
  213. (*idx)->status = MBUS_STATUS_ONLINE;
  214. m_pDBC->updateModBusRTU( (*idx)->id, (*idx)->status, (*idx)->c_InBits, (*idx)->c_OutBits );
  215. //Input Handling
  216. if ( (*idx)->c_InBits ) {
  217. bool had_some_assignments = false;
  218. //Testing Bits
  219. for ( uint8_t bi = 0; bi < 4; bi++ ) {
  220. if ( ((*idx)->c_InBits & ( 1 << bi ) ) == ( 1 << bi ) ) {
  221. //Bit is set
  222. if( (*idx)->crossbar[4+bi] ) { // Assigned Action For Bit
  223. // check functionality
  224. switch ( (*idx)->crossbar[4 + bi] ) {
  225. case MBUS_FUNC_ACK_UPPER_TRACK:{
  226. LOG("In: Upper Track ACK");
  227. uint64_t cTID = m_pDBC->getTrackIdByPlatform( (*idx)->platform_id, 'U' );
  228. if ( cTID ) {
  229. SESSION_DATA *tSData = servaSessionManager::getInstance()->getActiveSessionByTrack( cTID );
  230. if ( tSData ) {
  231. //Rate Session
  232. m_pDBC->updateSessionStatus( tSData->db_id, SCADA_ACK_SESSION_RATING );
  233. SESSION_RATE_DATA *tData = (SESSION_RATE_DATA *) malloc( sizeof( SESSION_RATE_DATA ) );
  234. if ( tData ) {
  235. tData->level = SCADA_ACK_SESSION_RATING;
  236. tData->track_id = (*idx)->platform_id;
  237. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_RATED, NULL, NULL, tData );
  238. if ( tEvt ) {
  239. basicEventHeap::getInstance()->broadcast( tEvt );
  240. } else {
  241. free( tData );
  242. };
  243. };
  244. free( tSData );
  245. };
  246. };
  247. break;
  248. };
  249. case MBUS_FUNC_ACK_BOTTOM_TRACK:{//Bottom Track
  250. LOG("In: Bottom Track ACK");
  251. uint64_t cTID = m_pDBC->getTrackIdByPlatform( (*idx)->platform_id, 'B' );
  252. if ( cTID ) {
  253. SESSION_DATA *tSData = servaSessionManager::getInstance()->getActiveSessionByTrack( cTID );
  254. if ( tSData ) {
  255. //Rate Session
  256. m_pDBC->updateSessionStatus( tSData->db_id, SCADA_ACK_SESSION_RATING );
  257. SESSION_RATE_DATA *tData = (SESSION_RATE_DATA *) malloc( sizeof( SESSION_RATE_DATA ) );
  258. if ( tData ) {
  259. tData->level = SCADA_ACK_SESSION_RATING;
  260. tData->track_id = (*idx)->platform_id;
  261. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_RATED, NULL, NULL, tData );
  262. if ( tEvt ) {
  263. basicEventHeap::getInstance()->broadcast( tEvt );
  264. } else {
  265. free( tData );
  266. };
  267. };
  268. free( tSData );
  269. };
  270. };
  271. break;
  272. };
  273. case MBUS_FUNC_ACK_PLATFORM_ALARMS:{//Both Tracks
  274. LOG("In: All Tracks ACK");
  275. bool triggered_by_direct_event = false;
  276. uint64_t cTID = m_pDBC->getTrackIdByPlatform( (*idx)->platform_id, 'U' );
  277. if ( cTID ) {
  278. SESSION_DATA *tSData = servaSessionManager::getInstance()->getActiveSessionByTrack( cTID );
  279. if ( tSData ) {
  280. //Rate Session
  281. m_pDBC->updateSessionStatus( tSData->db_id, SCADA_ACK_SESSION_RATING );
  282. SESSION_RATE_DATA *tData = (SESSION_RATE_DATA *) malloc( sizeof( SESSION_RATE_DATA ) );
  283. if ( tData ) {
  284. tData->level = SCADA_ACK_SESSION_RATING;
  285. tData->track_id = (*idx)->platform_id;
  286. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_RATED, NULL, NULL, tData );
  287. if ( tEvt ) {
  288. basicEventHeap::getInstance()->broadcast( tEvt );
  289. } else {
  290. free( tData );
  291. };
  292. };
  293. free( tSData );
  294. } else {
  295. // Use Just Clear Signals Event if no Active Session
  296. EVENT_CONTAINER * tEvt = createBasicEvent( (*idx)->platform_id, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_CLEAR_S );
  297. if ( tEvt ) {
  298. basicEventHeap::getInstance()->broadcast( tEvt );
  299. triggered_by_direct_event = true;
  300. };
  301. };
  302. };
  303. cTID = m_pDBC->getTrackIdByPlatform( (*idx)->platform_id, 'B' );
  304. if ( cTID ) {
  305. SESSION_DATA *tSData = servaSessionManager::getInstance()->getActiveSessionByTrack( cTID );
  306. if ( tSData ) {
  307. //Rate Session
  308. m_pDBC->updateSessionStatus( tSData->db_id, SCADA_ACK_SESSION_RATING );
  309. SESSION_RATE_DATA *tData = (SESSION_RATE_DATA *) malloc( sizeof( SESSION_RATE_DATA ) );
  310. if ( tData ) {
  311. tData->level = SCADA_ACK_SESSION_RATING;
  312. tData->track_id = (*idx)->platform_id;
  313. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_RATED, NULL, NULL, tData );
  314. if ( tEvt ) {
  315. basicEventHeap::getInstance()->broadcast( tEvt );
  316. } else {
  317. free( tData );
  318. };
  319. };
  320. free( tSData );
  321. } else {
  322. // Use Just Clear Signals Event if no Active Session
  323. // But no need to do it twice!
  324. if ( !triggered_by_direct_event ) {
  325. EVENT_CONTAINER * tEvt = createBasicEvent( (*idx)->platform_id, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_CLEAR_S );
  326. if ( tEvt ) {
  327. basicEventHeap::getInstance()->broadcast( tEvt );
  328. };
  329. };
  330. };
  331. };
  332. break;
  333. };
  334. case MBUS_FUNC_SIG_STROBE_LIGHT:{ // Set TCC AUX signal
  335. LOG("In: Strobe");
  336. MODBUS_POST_DATA *tData =(MODBUS_POST_DATA *) malloc( sizeof( MODBUS_POST_DATA ) );
  337. if ( tData ) {
  338. tData->type = SCADA_POST_TYPE_HELTH_STROBE;
  339. tData->status = 0;
  340. tData->src = (*idx)->func;
  341. tData->platform_id = (*idx)->platform_id;
  342. EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_STROBE, NULL, NULL, tData );
  343. if ( tEvt ) {
  344. basicEventHeap::getInstance()->broadcast( tEvt );
  345. } else {
  346. free( tData );
  347. };
  348. };
  349. break;
  350. };
  351. case MBUS_FUNC_ACK_ALL_SIGNALS:{
  352. // Do we need to search an active SESSION in that case ??
  353. LOG("In: Dismiss Platform");
  354. EVENT_CONTAINER * tEvt = createBasicEvent( (*idx)->platform_id, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_CLEAR_P );
  355. if ( tEvt ) {
  356. basicEventHeap::getInstance()->broadcast( tEvt );
  357. };
  358. break;
  359. };
  360. };
  361. had_some_assignments = true;
  362. };
  363. };
  364. };
  365. //Reset Latch - Only If the Crossbar has function for that
  366. if ( had_some_assignments ) {
  367. rv = modbus_set_rtu((*idx)->ip, (*idx)->port, 40, 0);
  368. if ( rv == -1 ) {
  369. LOG_ERROR("Error clear latch flag on RTU");
  370. };
  371. };
  372. };
  373. continue;
  374. };
  375. #ifdef DEBUG_EXTRA
  376. else LOG_ERROR("Read DI Failure");
  377. #endif
  378. }
  379. #ifdef DEBUG_EXTRA
  380. else LOG_ERROR("RTU Communication Failure");
  381. #endif
  382. (*idx)->status = MBUS_STATUS_OFFLINE;
  383. m_pDBC->updateModBusRTU( (*idx)->id, (*idx)->status, (*idx)->c_InBits, (*idx)->c_OutBits );
  384. };
  385. };
  386. #ifdef DEBUG_EXTRA
  387. LOG("Sync ModBus Modules Done");
  388. #endif
  389. oss = css; // Give 1 Second for STAGE_WORK ??
  390. m_bStage = MBUS_STAGE_WORK;
  391. [[fallthrough]];
  392. };
  393. case MBUS_STAGE_WORK:{
  394. uint64_t cts = getMilliseconds();
  395. m_mProtector.lock();
  396. if ( m_vActioItems.size() ) {
  397. for( V_MODBUS_ACION_ITEMS::iterator idx = m_vActioItems.begin(); idx != m_vActioItems.end(); ){
  398. if( (*idx)->scheduled_on < cts ) {
  399. MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU( (*idx)->module_id );
  400. if ( tRTU ) {
  401. if( handleRTU( tRTU, (*idx)->value, (*idx)->mask) ) {
  402. free( *idx );
  403. idx = m_vActioItems.erase( idx ); // erase() invalidates the iterator
  404. } else {
  405. LOG_ERROR("Cannot Issue SCADA Signal!");
  406. idx++;
  407. };
  408. free( tRTU );
  409. } else {
  410. LOG_ERROR("Cannot Get SCADA RTU info!");
  411. idx++;
  412. };
  413. } else idx++;
  414. };
  415. };
  416. m_mProtector.unlock();
  417. break;
  418. };
  419. case MBUS_STAGE_END:{
  420. m_bThreadStatus = TH_ENDED;
  421. break;
  422. };
  423. };
  424. if ( oss != css ) {
  425. //Each Second or as it takes .... Scan All RTUs may take longer!
  426. oss = css;
  427. m_bStage = MBUS_STAGE_SYNC;;
  428. };
  429. SLEEP(DEFAULT_THREAD_SLEEP_TIME);
  430. };
  431. };
  432. bool servaModBusManager::handleRTU( MODBUS_RTU_INFO *tRTU, uint8_t value, uint8_t mask ){
  433. bool rVal = false;
  434. if ( tRTU ) {
  435. if ( tRTU->status == MBUS_STATUS_ONLINE ) {
  436. bool act = false;
  437. if( ( tRTU->c_OutBits & value ) != value ) {
  438. //Set
  439. tRTU->c_OutBits |= value;
  440. act = true;
  441. };
  442. if( ( tRTU->c_OutBits & mask ) != 0 ) {
  443. //Clear
  444. tRTU->c_OutBits &= ~mask;
  445. act = true;
  446. };
  447. // Apply Changes at once
  448. if ( act ) {
  449. int rv = modbus_set_rtu(tRTU->ip, tRTU->port, tRTU->output_base_addr, tRTU->c_OutBits);
  450. if ( rv < 0 ) {
  451. m_pDBC->updateModBusRTU( tRTU->id, MBUS_STATUS_OFFLINE, 0, 0 );
  452. } else {
  453. m_pDBC->updateModBusRTU( tRTU->id, MBUS_STATUS_ONLINE, tRTU->c_InBits, tRTU->c_OutBits );
  454. rVal = true;
  455. };
  456. };
  457. };
  458. };
  459. return rVal;
  460. };
  461. bool servaModBusManager::validate(){
  462. MODBUS_MANAGER_DATA * tData = m_pDBC->getModBusManagerData();
  463. if ( tData ) {
  464. if( memcmp( &m_sManagerData, tData, sizeof( MODBUS_MANAGER_DATA ) ) != 0 ){
  465. #ifdef DEBUG
  466. LOG("Settings was changed ... reapplying");
  467. #endif
  468. memcpy( &m_sManagerData, tData, sizeof( MODBUS_MANAGER_DATA ) );
  469. m_bStage = MBUS_STAGE_INIT; // Reload Modules just in case
  470. };
  471. free( tData );
  472. };
  473. return true;
  474. };
  475. bool servaModBusManager::dispatchEvent( EVENT_CONTAINER *Evt ){
  476. if ( Evt == NULL ) return false;
  477. switch ( Evt->m_eType ) {
  478. case EVT_SRV_SESSION_STARTED:{
  479. LOG("EVT Session Start");
  480. if( m_sManagerData.automaticAlarmRisingTO ) {
  481. //setup Schedule
  482. LOG("Setup Scheduled Signal");
  483. SERVA_SESSION_EVT_DATA *tSData = (SERVA_SESSION_EVT_DATA *)Evt->m_pEvtData;
  484. if( tSData ) {
  485. LOG("Have Session Evt Data");
  486. SCADA_TRACK_INFO *tData = m_pDBC->getTrackSCADA(Evt->m_nSourceNodeID);
  487. if ( tData ) {
  488. LOG("Have Track Info");
  489. //MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU_Platform( tData->platform_id );
  490. uint8_t expected_module_functionality = 0;
  491. if ( tSData->side == 'L' || tSData->side == 'B' ) {
  492. expected_module_functionality |= 1;
  493. };
  494. if ( tSData->side == 'R' || tSData->side == 'B' ) {
  495. expected_module_functionality |= 2;
  496. };
  497. #ifdef DEBUG
  498. if ( expected_module_functionality ) LOG("Expect Module Function");
  499. #endif
  500. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU(tData->platform_id);
  501. if ( tIDS ) {
  502. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  503. LOG("Check Module!");
  504. MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU( *idx );
  505. if ( tRTU ) {
  506. uint8_t CBV = tRTU->crossbar[((tData->side == 'U')?MBUS_CROSSBAR_UPPER_TRACK:MBUS_CROSSBAR_BOTTOM_TRACK)];
  507. if( CBV ) { // 0 - disabled functionality
  508. CBV --; // correct DC bits order
  509. // 1 = left 2 = right 3 = tcc
  510. if( ( tRTU->func == 1 ) && ( ( expected_module_functionality & 1 ) == 1 ) ) {
  511. LOG("Using Left Module!");
  512. MODBUS_ACION_ITEM *tAI = (MODBUS_ACION_ITEM *)malloc(sizeof(MODBUS_ACION_ITEM));
  513. if ( tAI ) {
  514. memset( tAI, 0, sizeof(MODBUS_ACION_ITEM) );
  515. tAI->scheduled_on = getMilliseconds() + ( m_sManagerData.automaticAlarmRisingTO * 1000 );
  516. tAI->module_id = tRTU->id;
  517. tAI->value = ( 1 << CBV );
  518. m_mProtector.lock();
  519. m_vActioItems.push_back( tAI );
  520. m_mProtector.unlock();
  521. };
  522. };
  523. if( ( tRTU->func == 2 ) && ( ( expected_module_functionality & 2 ) == 2 ) ) {
  524. LOG("Using Right Module!");
  525. MODBUS_ACION_ITEM *tAI = (MODBUS_ACION_ITEM *)malloc(sizeof(MODBUS_ACION_ITEM));
  526. if ( tAI ) {
  527. memset( tAI, 0, sizeof(MODBUS_ACION_ITEM) );
  528. tAI->scheduled_on = getMilliseconds() + ( m_sManagerData.automaticAlarmRisingTO * 1000 );
  529. tAI->module_id = tRTU->id;
  530. tAI->value = ( 1 << CBV );
  531. m_mProtector.lock();
  532. m_vActioItems.push_back( tAI );
  533. m_mProtector.unlock();
  534. };
  535. };
  536. if( tRTU->func == 3 ) { // TCC does always
  537. LOG("Have TCC Module!");
  538. MODBUS_ACION_ITEM *tAI = (MODBUS_ACION_ITEM *)malloc(sizeof(MODBUS_ACION_ITEM));
  539. if ( tAI ) {
  540. memset( tAI, 0, sizeof(MODBUS_ACION_ITEM) );
  541. tAI->scheduled_on = getMilliseconds() + ( m_sManagerData.automaticAlarmRisingTO * 1000 );
  542. tAI->module_id = tRTU->id;
  543. tAI->value = ( 1 << CBV );
  544. m_mProtector.lock();
  545. m_vActioItems.push_back( tAI );
  546. m_mProtector.unlock();
  547. };
  548. };
  549. }; // Crossbar check
  550. free( tRTU );
  551. };
  552. };
  553. delete( tIDS );
  554. };
  555. free( tData );
  556. };
  557. };
  558. };
  559. break;
  560. };
  561. case EVT_SRV_SESSION_ENDED:{ // Ignore Session End since The SCADA signal must be disabled only by operator
  562. if ( m_sManagerData.supressSignalBySessionEnd ) {
  563. LOG("EVT Session Ended");
  564. SCADA_TRACK_INFO *tData = m_pDBC->getTrackSCADA( Evt->m_nSourceNodeID );
  565. if ( tData ) {
  566. //MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU_Platform( tData->platform_id );
  567. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( tData->platform_id );
  568. if ( tIDS ) {
  569. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  570. mitigateCoil( *idx, ((tData->side == 'U')?MBUS_CROSSBAR_UPPER_TRACK:MBUS_CROSSBAR_BOTTOM_TRACK ) );
  571. };
  572. delete( tIDS );
  573. };
  574. free( tData );
  575. };
  576. };
  577. break;
  578. };
  579. case EVT_SRV_SESSION_RATED:{
  580. if ( Evt->m_pEvtData == NULL ) return false;
  581. if ( m_sManagerData.hazardSignalLevel ) {
  582. SESSION_RATE_DATA *tSRD = (SESSION_RATE_DATA *)Evt->m_pEvtData;
  583. SCADA_TRACK_INFO *tData = m_pDBC->getTrackSCADA( tSRD->track_id );
  584. if ( tData ) {
  585. //MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU_Platform( tData->platform_id );
  586. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( tData->platform_id );
  587. if ( tIDS ) {
  588. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  589. MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU( *idx );
  590. if ( tRTU ) {
  591. uint8_t CBV = tRTU->crossbar[((tData->side == 'U')?MBUS_CROSSBAR_UPPER_TRACK:MBUS_CROSSBAR_BOTTOM_TRACK)];
  592. if ( CBV ) {
  593. CBV--;
  594. uint8_t bON = (1 << CBV );
  595. uint8_t bOFF = ~( 1 << CBV );
  596. //Remove Scheduled Signal change
  597. m_mProtector.lock();
  598. for ( V_MODBUS_ACION_ITEMS::iterator idd=m_vActioItems.begin(); idd!=m_vActioItems.end(); ){
  599. //check if shceduled ActionItem is Assigned to Current RTU
  600. if( (*idd)->module_id == tRTU->id ) {
  601. if( (((*idd)->value & bON ) == bON ) || (((*idd)->mask & bOFF ) == bOFF ) ){
  602. free((*idd));
  603. idd = m_vActioItems.erase( idd ); // erase() invalidates the iterator
  604. } else idd++;
  605. } else idd++;
  606. };
  607. m_mProtector.unlock();
  608. if ( tSRD->level < m_sManagerData.hazardSignalLevel ) {
  609. //Clear Signal if Set
  610. if ( (tRTU->c_OutBits & bON ) == bON ) {
  611. tRTU->c_OutBits &= bOFF;
  612. int rv = modbus_set_rtu( tRTU->ip, tRTU->port, tRTU->output_base_addr, tRTU->c_OutBits );
  613. if ( rv < 0 ) {
  614. m_pDBC->updateModBusRTU( tRTU->id, MBUS_STATUS_OFFLINE, 0, 0 );
  615. } else {
  616. m_pDBC->updateModBusRTU( tRTU->id, MBUS_STATUS_ONLINE, tRTU->c_InBits, tRTU->c_OutBits );
  617. };
  618. };
  619. } else {
  620. //Set Signal if was Cleared
  621. if ( (tRTU->c_OutBits & bON ) == 0 ) {
  622. tRTU->c_OutBits |= bON;
  623. int rv = modbus_set_rtu( tRTU->ip, tRTU->port, tRTU->output_base_addr, tRTU->c_OutBits );
  624. if ( rv < 0 ) {
  625. m_pDBC->updateModBusRTU( tRTU->id, MBUS_STATUS_OFFLINE, 0, 0 );
  626. } else {
  627. m_pDBC->updateModBusRTU( tRTU->id, MBUS_STATUS_ONLINE, tRTU->c_InBits, tRTU->c_OutBits );
  628. };
  629. };
  630. };
  631. };// Crossbar Check
  632. free( tRTU );
  633. };
  634. };
  635. delete(tIDS);
  636. };
  637. free( tData );
  638. };
  639. };
  640. break;
  641. };
  642. // Do we need that functionality ??
  643. case EVT_SRV_MODBUS_TEST_P:{
  644. MODBUS_TEST_DATA *tData = (MODBUS_TEST_DATA *)Evt->m_pEvtData;
  645. if ( tData ) {
  646. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( tData->id );
  647. if ( tIDS ) {
  648. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  649. MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU( *idx );
  650. if ( tRTU ) {
  651. #ifdef DEBUG_EXTRA
  652. char tB[200];
  653. sprintf( tB, "%s:%d 0x%02x 0x%02x", tRTU->ip, tRTU->port, tRTU->output_base_addr, tData->c_OutBits );
  654. LOG( tB );
  655. #endif
  656. int rv = modbus_set_rtu( tRTU->ip, tRTU->port, tRTU->output_base_addr, tData->c_OutBits );
  657. if ( rv < 0 ) {
  658. m_pDBC->updateModBusRTU( tRTU->id, MBUS_STATUS_OFFLINE, 0, 0 );
  659. } else {
  660. m_pDBC->updateModBusRTU( tRTU->id, MBUS_STATUS_ONLINE, tRTU->c_InBits, tData->c_OutBits );
  661. };
  662. free( tRTU );
  663. };
  664. };
  665. delete( tIDS );
  666. };
  667. };
  668. return false; // No need Propogate this Evt
  669. };
  670. case EVT_SRV_MODBUS_TEST_M:{
  671. MODBUS_TEST_DATA *tData = (MODBUS_TEST_DATA *)Evt->m_pEvtData;
  672. if ( tData ) {
  673. MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU( tData->id );
  674. if ( tRTU ) {
  675. #ifdef DEBUG_EXTRA
  676. char tB[200];
  677. sprintf( tB, "%s:%d 0x%02x 0x%02x", tRTU->ip, tRTU->port, tRTU->output_base_addr, tData->c_OutBits );
  678. LOG( tB );
  679. #endif
  680. handleRTU( tRTU, tData->c_OutBits, ~tData->c_OutBits );
  681. free( tRTU );
  682. };
  683. };
  684. return false; // No need Propogate this Evt
  685. };
  686. case EVT_SRV_MODBUS_CLEAR_S:{
  687. //Create ActionItems For all Modules
  688. LOG("Clear ALARMS Only");
  689. uint64_t platform_id = Evt->m_nSourceNodeID;
  690. if ( platform_id ) {
  691. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( platform_id );
  692. if ( tIDS ) {
  693. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  694. mitigateCoil( *idx, MBUS_CROSSBAR_UPPER_TRACK );
  695. mitigateCoil( *idx, MBUS_CROSSBAR_BOTTOM_TRACK );
  696. };
  697. delete( tIDS );
  698. };
  699. };
  700. return false;// No need Propogate this Evt ??
  701. };
  702. case EVT_SRV_MODBUS_CLEAR_P:{
  703. //Create ActionItems For all Modules
  704. LOG("Clear ALL SIGNALS and SNOOZE POSTBOXES");
  705. uint64_t platform_id = Evt->m_nSourceNodeID;
  706. if ( platform_id ) {
  707. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( platform_id );
  708. if ( tIDS ) {
  709. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  710. mitigateCoil( *idx, MBUS_CROSSBAR_UPPER_TRACK );
  711. mitigateCoil( *idx, MBUS_CROSSBAR_BOTTOM_TRACK );
  712. mitigateCoil( *idx, MBUS_CROSSBAR_HEALTH, 0, (SERVER_SCADA_POST_TYPE) 0 );
  713. mitigateCoil( *idx, MBUS_CROSSBAR_AUX, 0, (SERVER_SCADA_POST_TYPE) 6 );
  714. };
  715. delete( tIDS );
  716. };
  717. };
  718. return false; // No need Propogate this Evt ??
  719. };
  720. case EVT_SRV_MODBUS_S_POSTBOX:{
  721. LOG("Snooze PBOX");
  722. MODBUS_POST_DATA *sData = (MODBUS_POST_DATA *)Evt->m_pEvtData;
  723. if ( sData ) {
  724. bool mitigate = false;
  725. if ( sData->type == 6 ) {
  726. mitigate = true;
  727. } else {
  728. if ( sData->type >= m_sManagerData.helthSignalLevel ) mitigate = true;
  729. };
  730. if ( mitigate ) {
  731. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( sData->platform_id );
  732. if ( tIDS ) {
  733. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  734. mitigateCoil(*idx, ((sData->type == SCADA_POST_TYPE_HELTH_STROBE) ? MBUS_CROSSBAR_AUX : MBUS_CROSSBAR_HEALTH), sData->src, (SERVER_SCADA_POST_TYPE)sData->type );
  735. };
  736. delete( tIDS );
  737. };
  738. };
  739. };
  740. break;
  741. };
  742. case EVT_SRV_MODBUS_D_POSTBOX:{
  743. LOG("Dismiss PBOX");
  744. MODBUS_POST_DATA *sData = (MODBUS_POST_DATA *)Evt->m_pEvtData;
  745. if ( sData ) {
  746. bool mitigate = false;
  747. if ( sData->type == 6 ) {
  748. mitigate = true;
  749. } else {
  750. if ( sData->type >= m_sManagerData.helthSignalLevel ) mitigate = true;
  751. };
  752. if ( mitigate ) {
  753. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( sData->platform_id );
  754. if ( tIDS ) {
  755. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  756. mitigateCoil(*idx, ((sData->type == SCADA_POST_TYPE_HELTH_STROBE) ? MBUS_CROSSBAR_AUX : MBUS_CROSSBAR_HEALTH), sData->src, (SERVER_SCADA_POST_TYPE)sData->type );
  757. };
  758. delete( tIDS );
  759. };
  760. };
  761. };
  762. return false; // No need Propogate this Evt
  763. };
  764. case EVT_SRV_MODULE_HEALTH:{
  765. LOG("Module Helth Changed!");
  766. if ( Evt->m_pEvtData == NULL ) return false;
  767. if ( m_sManagerData.helthSignalLevel ) {
  768. MODULE_HEALTH_STATUS *tData = (MODULE_HEALTH_STATUS *)Evt->m_pEvtData;
  769. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( tData->platform_id );
  770. if ( tIDS ) {
  771. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  772. if( tData->status >= m_sManagerData.helthSignalLevel ){
  773. activateCoil( *idx, MBUS_CROSSBAR_HEALTH, tData->module_id, (SERVER_SCADA_POST_TYPE) tData->status );
  774. } else {
  775. mitigateCoil( *idx, MBUS_CROSSBAR_HEALTH, tData->module_id, (SERVER_SCADA_POST_TYPE) tData->status );
  776. };
  777. };
  778. delete( tIDS );
  779. };
  780. };
  781. break;
  782. };
  783. case EVT_SRV_MODBUS_STROBE:{
  784. LOG("Activate Strobe Signal");
  785. MODBUS_POST_DATA *tData = (MODBUS_POST_DATA *) Evt->m_pEvtData;
  786. if ( tData ) {
  787. DBC_UINT64_LIST *tIDS = m_pDBC->listPlatformModBusRTU( tData->platform_id );
  788. if ( tIDS ) {
  789. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  790. activateCoil( *idx, MBUS_CROSSBAR_AUX, tData->src, (SERVER_SCADA_POST_TYPE) tData->type );
  791. };
  792. delete( tIDS );
  793. };
  794. };
  795. break;
  796. };
  797. };
  798. return true;
  799. };
  800. bool servaModBusManager::validateHealthAction( uint64_t platform_id, bool action ){
  801. bool retVal = true;
  802. if( platform_id ) {
  803. DBC_UINT64_LIST *tIDS = m_pDBC->listScadaPosts( platform_id );
  804. if ( tIDS ) {
  805. for ( DBC_UINT64_LIST::iterator idx=tIDS->begin(); idx != tIDS->end(); idx++ ) {
  806. MODBUS_POST_DATA *tData = m_pDBC->getScadaPostData( *idx );
  807. if ( tData ) {
  808. if ( !action ) {
  809. // Have Some Unresolved Health Status on Platform
  810. if ( ( tData->type < 6 ) && ( tData->status == 0 ) ) retVal = false;
  811. };
  812. free(tData);
  813. };
  814. };
  815. delete( tIDS );
  816. };
  817. };
  818. return retVal;
  819. };
  820. void servaModBusManager::activateCoil( uint64_t rtu_id, uint8_t function_id, uint64_t src, SERVER_SCADA_POST_TYPE pt ){
  821. if( function_id > MBUS_CROSSBAR_AUX ) return; // No such Function
  822. MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU( rtu_id );
  823. if ( tRTU ) {
  824. uint8_t CBV = tRTU->crossbar[function_id];
  825. if( CBV ) {
  826. bool module_is_ok = true;
  827. if( pt && tRTU->func != 3 && tRTU->func != 0 && CBV ) module_is_ok = false;
  828. // check if TCC or Default Module
  829. if( module_is_ok ) {
  830. int c_status = 0;
  831. // check if was not snoozed by operator
  832. if( pt ) c_status = m_pDBC->getScadaPostStatus( tRTU->platform_id, pt, src );
  833. if ( function_id == MBUS_CROSSBAR_HEALTH ) {
  834. // clear all abowe Health statuses as not relevant
  835. // do we need a module ID ?? since the zone is whole platform
  836. // If tData->status == 0 then the Health status will be cleared
  837. char tB[128];
  838. sprintf( tB, "Clearing All Abowe Health level %d on Activate", pt );
  839. LOG( tB );
  840. m_pDBC->deleteScadaPostsAbowe( tRTU->platform_id, pt, src );
  841. };
  842. if( c_status < 1) { // Not Snoozed by Operator
  843. if ( c_status < 0 ) { // Not Founud in MBOX but must have record!
  844. m_pDBC->addScadaPost( tRTU->platform_id, pt, src );
  845. };
  846. CBV--;
  847. //Actual Setting modbus signal
  848. uint8_t bON = (1 << CBV );
  849. uint8_t bOFF = ~( 1 << CBV );
  850. //Remove Scheduled Signal change
  851. m_mProtector.lock();
  852. for ( V_MODBUS_ACION_ITEMS::iterator idz=m_vActioItems.begin(); idz!=m_vActioItems.end(); ){
  853. if( (*idz)->module_id == tRTU->id ) {
  854. //check if shceduled signal is current
  855. if( (((*idz)->value & bON ) == bON ) || (((*idz)->mask & bOFF ) == bOFF ) ){
  856. free((*idz));
  857. idz = m_vActioItems.erase( idz ); // erase() invalidates the iterator
  858. } else idz++;
  859. //break;
  860. } else idz++;
  861. };
  862. m_mProtector.unlock();
  863. //Since Activation need to set only SET
  864. handleRTU( tRTU, bON, 0x00 );
  865. };
  866. };
  867. };
  868. free( tRTU );
  869. };
  870. };
  871. void servaModBusManager::mitigateCoil( uint64_t rtu_id, uint8_t function_id, uint64_t src, SERVER_SCADA_POST_TYPE pt ){
  872. if( function_id > MBUS_CROSSBAR_AUX ) return; // No such Function
  873. MODBUS_RTU_INFO *tRTU = m_pDBC->getModBusRTU( rtu_id );
  874. if ( tRTU ) {
  875. uint8_t CBV = tRTU->crossbar[function_id];
  876. if ( CBV ) {
  877. if (function_id == MBUS_CROSSBAR_HEALTH) {
  878. // clear all abowe Health statuses as not relevant
  879. // do we need a module ID ?? since the zone is whole platform
  880. // If tData->status == 0 then the Health status will be cleared
  881. char tB[128];
  882. sprintf( tB, "Clearing All Abowe Health level %d for %lld on Mitigate ", pt, src );
  883. LOG( tB );
  884. if ( pt ) {
  885. m_pDBC->deleteScadaPostsAbowe(tRTU->platform_id, (SERVER_SCADA_POST_TYPE) pt, src ); // pt-1 - to remove above and current
  886. } else {
  887. m_pDBC->deleteScadaPostsAbowe(tRTU->platform_id, SCADA_POST_TYPE_NA, 0 ); // Clear All Platform Posts!!
  888. };
  889. };
  890. LOG("Validating Health Action");
  891. if ( validateHealthAction( tRTU->platform_id, false ) ) {
  892. CBV--;
  893. //Actual Setting modbus signal
  894. uint8_t bON = (1 << CBV );
  895. uint8_t bOFF = ~bON;
  896. //Remove Scheduled Signal change
  897. m_mProtector.lock();
  898. for ( V_MODBUS_ACION_ITEMS::iterator idz=m_vActioItems.begin(); idz!=m_vActioItems.end(); ){
  899. if( (*idz)->module_id == tRTU->id ) {
  900. //check if shceduled signal is current
  901. if( (((*idz)->value & bON ) == bON ) || (((*idz)->mask & bOFF ) == bOFF ) ){
  902. free((*idz));
  903. idz = m_vActioItems.erase( idz ); // erase() invalidates the iterator
  904. } else idz++;
  905. //break;
  906. } else idz++;
  907. };
  908. m_mProtector.unlock();
  909. //Since Mitigation need to set only mask
  910. handleRTU( tRTU, 0x00, bON );
  911. };
  912. };
  913. free( tRTU );
  914. };
  915. }
  916. #undef LOG
  917. #undef LOG_ERROR