Blame view

src/ModbusAdapter.cpp 8.89 KB
783ce3c5   Peter M. Groen   Setting up workin...
1
2
3
  /*****************************************************************************
   * Copyright (c) 2022 Priva b.v.
   *****************************************************************************/
cadcf24a   Peter M. Groen   Setting up workin...
4
5
  
  #include "ConnectionConfig.h"
783ce3c5   Peter M. Groen   Setting up workin...
6
  #include "modbus.h"
cadcf24a   Peter M. Groen   Setting up workin...
7
  #include "ModbusAdapter.h"
783ce3c5   Peter M. Groen   Setting up workin...
8
  #include "privautils/PrivaLogger.h"
cadcf24a   Peter M. Groen   Setting up workin...
9
10
11
  
  #include <cstring>  /// Added for memset functionality
  
783ce3c5   Peter M. Groen   Setting up workin...
12
13
  
  
cadcf24a   Peter M. Groen   Setting up workin...
14
15
16
  ModbusAdapter::ModbusAdapter()
      : m_modbus( nullptr )
  {
cadcf24a   Peter M. Groen   Setting up workin...
17
18
19
20
21
22
23
  }
  
  ModbusAdapter::~ModbusAdapter()
  {
  
  }
  
783ce3c5   Peter M. Groen   Setting up workin...
24
  bool ModbusAdapter::ModbusConnect( const ConnectionConfig &config )
cadcf24a   Peter M. Groen   Setting up workin...
25
26
27
  {
      if( m_connected )
      {
b85a3e4a   Peter M. Groen   Setting up workin...
28
          this->ModbusDisconnect();   // Will already set m_connected
cadcf24a   Peter M. Groen   Setting up workin...
29
30
      }
  
783ce3c5   Peter M. Groen   Setting up workin...
31
      m_connType = config.getType();
cadcf24a   Peter M. Groen   Setting up workin...
32
33
34
35
  
      switch( m_connType )
      {
          case ConnectionType::CT_SERIAL:
783ce3c5   Peter M. Groen   Setting up workin...
36
37
38
              m_connected = this->ModbusConnectRTU( config.getPort(), config.getBaudRate(),
                                                    config.getParity(), config.getDataBits(),
                                                    config.getStopBits(), config.getTimeOut());
cadcf24a   Peter M. Groen   Setting up workin...
39
40
41
              break;
  
          case ConnectionType::CT_TCP:
783ce3c5   Peter M. Groen   Setting up workin...
42
              m_connected = this->ModbusConnectTCP( config.getIpAddress(), config.getTcpPort(), 10 );
cadcf24a   Peter M. Groen   Setting up workin...
43
44
45
46
47
48
              break;
  
          default:
              // throw a sensible message or return an errorcode.
              break;
      }
b85a3e4a   Peter M. Groen   Setting up workin...
49
      return m_connected;
cadcf24a   Peter M. Groen   Setting up workin...
50
51
  }
  
b85a3e4a   Peter M. Groen   Setting up workin...
52
  bool ModbusAdapter::ModbusDisconnect()
cadcf24a   Peter M. Groen   Setting up workin...
53
54
55
56
57
58
59
60
61
62
63
  {
      if( m_modbus != nullptr )
      {
          if( m_connected )
          {
              modbus_close( m_modbus );
              modbus_free( m_modbus );
          }
          // Clean up after ourselves.
          m_modbus = nullptr;
      }
b85a3e4a   Peter M. Groen   Setting up workin...
64
  
cadcf24a   Peter M. Groen   Setting up workin...
65
      m_connected = false;
b85a3e4a   Peter M. Groen   Setting up workin...
66
      return true;
cadcf24a   Peter M. Groen   Setting up workin...
67
68
69
70
71
72
73
74
75
76
  }
  
  modbusData ModbusAdapter::ModbusReadData( int slaveId, int functionCode, int startAddress, int noOfItems )
  {
      if( m_modbus == nullptr )
      {
          // No context
          return modbusData();
      }
  
cadcf24a   Peter M. Groen   Setting up workin...
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
      int resultValue = -1;
      bool is16Bit = false;
  
      modbus_set_slave( m_modbus, slaveId );
  
      // Request data from modbus.
      switch( functionCode )
      {
          case MODBUS_FC_READ_COILS:
              resultValue = modbus_read_bits( m_modbus, startAddress, noOfItems, m_dest );
              break;
          case MODBUS_FC_READ_DISCRETE_INPUTS:
              resultValue = modbus_read_input_bits( m_modbus, startAddress, noOfItems, m_dest );
              break;
          case MODBUS_FC_READ_HOLDING_REGISTERS:
              resultValue = modbus_read_registers( m_modbus, startAddress, noOfItems, m_dest16 );
              break;
          case MODBUS_FC_READ_INPUT_REGISTERS:
              resultValue = modbus_read_input_registers( m_modbus, startAddress, noOfItems, m_dest16 );
              break;
  
          default:
              break;
  
      }
  
      // Read the databuffers
      if( resultValue != noOfItems )
      {
          return modbusData();
      }
  
      modbusData resultData;
      for( int index = 0; index < noOfItems; ++index )
      {
          resultData.push_back( (is16Bit ? static_cast<uint16_t>(m_dest16[index]) : static_cast<uint16_t>(m_dest[index])) );
      }
  
      modbus_flush( m_modbus );   // flush data
      this->ClearBuffers();
  
      return resultData;
  }
  
  modbusData ModbusAdapter::ModbusReadHoldReg( int slaveId, int startAddress, int noOfItems )
  {
      if( m_modbus == nullptr )
      {
          return modbusData();
      }
  
      int resultValue = -1;       /// Return value from read functions
  
      // -- Start Critical Section --- ?? //
  
      modbus_set_slave( m_modbus, slaveId );
      /// Request data from modbus
      resultValue = modbus_read_registers( m_modbus, startAddress, noOfItems, m_dest16 );
  
      /// Read the databuffers
      if( resultValue != noOfItems )
      {
          return modbusData();
      }
  
      modbusData resultData;
      for( int index = 0; index < noOfItems; ++index )
      {
          resultData.push_back( static_cast<uint16_t>(m_dest16[index]) );
      }
  
      modbus_flush( m_modbus );
cadcf24a   Peter M. Groen   Setting up workin...
149
150
151
152
153
154
155
156
157
158
  
      // -- End Critical Section --- ?? //
  
      return resultData;
  }
  
  void ModbusAdapter::ModBusWriteData( int slaveId, int functionCode, int startAddress, int noOfItems, std::vector<int>values )
  {
      if( m_modbus == nullptr )
      {
b85a3e4a   Peter M. Groen   Setting up workin...
159
          // No modbus context. Sensible log-line and exit.
cadcf24a   Peter M. Groen   Setting up workin...
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
          return;
      }
  
      // ------------------------------------------------
      // Create 8 bits databuffer
      auto * data8 = new uint8_t[noOfItems];
      for( int index = 0; index < noOfItems; ++index )
      {
          data8[index] = values[index];
      }
  
      // Create same buffer for 16 bits data
      auto * data16 = new uint8_t[noOfItems];
      for( int index = 0; index < noOfItems; ++index )
      {
          data16[index] = values[index];
      }
      // ------------------------------------------------
  
      int resultValue = -1;
  
      modbus_set_slave( m_modbus, slaveId );
  
      // Request data from modbus
      switch( functionCode )
      {
          case MODBUS_FC_WRITE_SINGLE_COIL:
              resultValue = modbus_write_bit( m_modbus, startAddress, values[0] );
              noOfItems = 1;
              break;
          case MODBUS_FC_WRITE_SINGLE_REGISTER:
              resultValue = modbus_write_register( m_modbus, startAddress, values[0] );
              noOfItems = 1;
              break;
          case MODBUS_FC_WRITE_MULTIPLE_COILS:
  
              resultValue = modbus_write_bits( m_modbus, startAddress, noOfItems, data8 );
              break;
          case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
              resultValue = modbus_write_bits( m_modbus, startAddress, noOfItems, data16 );
              break;
      }
  
cadcf24a   Peter M. Groen   Setting up workin...
203
204
205
206
207
208
209
210
211
212
213
214
215
      modbus_flush(m_modbus); // Flush data.
  
      if( resultValue != noOfItems )
      {
          // Create a log line that writing the register failed. Maybe increment ErrorCounter(s)
      }
  }
  
  bool ModbusAdapter::isConnected() const
  {
      return m_connected;
  }
  
46785270   Peter M. Groen   Setting up workin...
216
  std::string ModbusAdapter::ErrorString( int errnum ) const
cadcf24a   Peter M. Groen   Setting up workin...
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
  {
      switch(errnum)
      {
          case EINVAL:
              return "Protocol context is NULL";
              break;
          case ETIMEDOUT:
              return "Timeout";
              break;
          case ECONNRESET:
              return "Connection reset";
              break;
          case ECONNREFUSED:
              return "Connection refused";
              break;
          case EPIPE:
              return "Socket error";
              break;
          default:
              return modbus_strerror(errno);
      }
  }
  
  /* ============= PRIVATE METHODS ============= */
783ce3c5   Peter M. Groen   Setting up workin...
241
  bool ModbusAdapter::ModbusConnectRTU( const std::string &serialport, int baud, char parity, int dataBits, int stopBits, int timeOut )
cadcf24a   Peter M. Groen   Setting up workin...
242
  {
783ce3c5   Peter M. Groen   Setting up workin...
243
244
245
246
247
248
249
250
251
252
      {   // Keep logging scope as short as possible
          std::string logLine( "Connecting : " + serialport + " ( "
                              + std::to_string( baud ) + " : "
                              + std::to_string( dataBits ) + ","
                              + std::string( parity ) + " "
                              + std::to_string( stopBits ) + " ) with timeout : "
                              + std::to_string( timeout * 0.1 ) + " seconds." );
          PRIVALOG_INFO(this->logZone, logLine );
      }
      m_modbus = modbus_new_rtu( serialport.c_str(), baud, parity, dataBits, stopBits );
cadcf24a   Peter M. Groen   Setting up workin...
253
254
255
256
257
258
259
260
261
  
  #ifdef LIB_MODBUS_DEBUG_OUTPUT
      // Do sensible logging through PRIVA_LOG
      m_modbus_set_debug( m_modbus, 1 );
  #endif
      if( m_modbus == nullptr )
      {
          // We can stop here. Nothing to be done as we don't have a valid context
          // Log to PRIVA_LOG
b85a3e4a   Peter M. Groen   Setting up workin...
262
263
          m_connected = false;
          return m_connected;
cadcf24a   Peter M. Groen   Setting up workin...
264
265
266
267
268
269
270
      }
      else if( m_modbus && modbus_connect( m_modbus ) == -1 )
      {
          // We could not connect to the selected serial port.
          // We can stop here. Nothing to be done as we don't have a valid connection
          modbus_free( m_modbus );
          m_connected = false;
b85a3e4a   Peter M. Groen   Setting up workin...
271
          return m_connected;
cadcf24a   Peter M. Groen   Setting up workin...
272
273
      }
  
b85a3e4a   Peter M. Groen   Setting up workin...
274
275
      m_connected = true;
  
cadcf24a   Peter M. Groen   Setting up workin...
276
      // Set recovery mode
783ce3c5   Peter M. Groen   Setting up workin...
277
      modbus_set_error_recovery( m_modbus, MODBUS_ERROR_RECOVERY_PROTOCOL | MODBUS_ERROR_RECOVERY_LINK );
cadcf24a   Peter M. Groen   Setting up workin...
278
279
280
281
  
      // Set the response timeout
      modbus_set_response_timeout( m_modbus, timeOut, 0 );
  
b85a3e4a   Peter M. Groen   Setting up workin...
282
      return m_connected;
cadcf24a   Peter M. Groen   Setting up workin...
283
284
  }
  
b85a3e4a   Peter M. Groen   Setting up workin...
285
  bool ModbusAdapter::ModbusConnectTCP( const std::string &ip, int port, int timeOut )
cadcf24a   Peter M. Groen   Setting up workin...
286
287
288
289
  {
      if( ip.empty() )
      {
          // Nothing to be done. Set an Logline to PRIVA_LOG and exit.
b85a3e4a   Peter M. Groen   Setting up workin...
290
          return false;
cadcf24a   Peter M. Groen   Setting up workin...
291
292
293
294
295
296
297
298
299
300
301
302
303
      }
  
      m_modbus = modbus_new_tcp( ip.c_str(), port );
  
  #ifdef LIB_MODBUS_DEBUG_OUTPUT
      // Do sensible logging through PRIVA_LOG
      m_modbus_set_debug( m_modbus, 1 );
  #endif
  
      if( m_modbus == nullptr )
      {
          // We can stop here. Nothing to be done as we don't have a valid context
          // Log to PRIVA_LOG
b85a3e4a   Peter M. Groen   Setting up workin...
304
          return false;
cadcf24a   Peter M. Groen   Setting up workin...
305
306
307
308
309
310
311
      }
      else if( m_modbus && modbus_connect( m_modbus ) == -1 )
      {
          // We could not connect to the selected serial port.
          // We can stop here. Nothing to be done as we don't have a valid connection
          modbus_free( m_modbus );
          m_connected = false;
b85a3e4a   Peter M. Groen   Setting up workin...
312
          return m_connected;
cadcf24a   Peter M. Groen   Setting up workin...
313
314
      }
  
b85a3e4a   Peter M. Groen   Setting up workin...
315
316
      m_connected = true;
  
cadcf24a   Peter M. Groen   Setting up workin...
317
      // Set recovery mode
783ce3c5   Peter M. Groen   Setting up workin...
318
      modbus_set_error_recovery( m_modbus, MODBUS_ERROR_RECOVERY_PROTOCOL | MODBUS_ERROR_RECOVERY_LINK );
cadcf24a   Peter M. Groen   Setting up workin...
319
320
321
322
  
      // Set the response timeout
      modbus_set_response_timeout( m_modbus, timeOut, 0 );
  
b85a3e4a   Peter M. Groen   Setting up workin...
323
      return m_connected;
cadcf24a   Peter M. Groen   Setting up workin...
324
  }