forked from fz-lyu/modbuspp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modbus.h
608 lines (531 loc) · 16.7 KB
/
modbus.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
149
150
151
152
153
154
155
156
157
158
159
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//
// Created by Fanzhe on 5/28/2017.
//
#ifndef MODBUSPP_MODBUS_H
#define MODBUSPP_MODBUS_H
#include <cstring>
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAX_MSG_LENGTH 260
///Function Code
#define READ_COILS 0x01
#define READ_INPUT_BITS 0x02
#define READ_REGS 0x03
#define READ_INPUT_REGS 0x04
#define WRITE_COIL 0x05
#define WRITE_REG 0x06
#define WRITE_COILS 0x0F
#define WRITE_REGS 0x10
///Exception Codes
#define EX_ILLEGAL_FUNCTION 0x01 // Function Code not Supported
#define EX_ILLEGAL_ADDRESS 0x02 // Output Address not exists
#define EX_ILLEGAL_VALUE 0x03 // Output Value not in Range
#define EX_SERVER_FAILURE 0x04 // Slave Deive Fails to process request
#define EX_ACKNOWLEDGE 0x05 // Service Need Long Time to Execute
#define EX_SERVER_BUSY 0x06 // Server Was Unable to Accept MB Request PDU
#define EX_NEGATIVE_ACK 0x07
#define EX_MEM_PARITY_PROB 0x08
#define EX_GATEWAY_PROBLEMP 0x0A // Gateway Path not Available
#define EX_GATEWYA_PROBLEMF 0x0B // Target Device Failed to Response
#define EX_BAD_DATA 0XFF // Bad Data lenght or Address
#define BAD_CON -1
/// Modbus Operator Class
/**
* Modbus Operator Class
* Providing networking support and mobus operation support.
*/
class modbus {
private:
bool _connected{};
uint16_t PORT{};
int _socket{};
uint _msg_id{};
int _slaveid{};
std::string HOST;
struct sockaddr_in _server{};
inline void modbus_build_request(uint8_t *to_send, uint address, int func) const;
int modbus_read(int address, uint amount, int func);
int modbus_write(int address, uint amount, int func, const uint16_t *value);
inline ssize_t modbus_send(uint8_t *to_send, int length);
inline ssize_t modbus_receive(uint8_t *buffer) const;
void modbuserror_handle(const uint8_t *msg, int func);
inline void set_bad_con();
inline void set_bad_input();
public:
bool err{};
int err_no{};
std::string error_msg;
modbus(std::string host, uint16_t port);
~modbus();
bool modbus_connect();
void modbus_close() const;
void modbus_set_slave_id(int id);
int modbus_read_coils(int address, int amount, bool* buffer);
int modbus_read_input_bits(int address, int amount, bool* buffer);
int modbus_read_holding_registers(int address, int amount, uint16_t *buffer);
int modbus_read_input_registers(int address, int amount, uint16_t *buffer);
int modbus_write_coil(int address, const bool& to_write);
int modbus_write_register(int address, const uint16_t& value);
int modbus_write_coils(int address, int amount, const bool *value);
int modbus_write_registers(int address, int amount, const uint16_t *value);
};
/**
* Main Constructor of Modbus Connector Object
* @param host IP Address of Host
* @param port Port for the TCP Connection
* @return A Modbus Connector Object
*/
modbus::modbus(std::string host, uint16_t port=502) {
HOST = host;
PORT = port;
_slaveid = 1;
_msg_id = 1;
_connected = false;
err = false;
err_no = 0;
error_msg = "";
}
/**
* Destructor of Modbus Connector Object
*/
modbus::~modbus(void) = default;
/**
* Modbus Slave ID Setter
* @param id ID of the Modbus Server Slave
*/
void modbus::modbus_set_slave_id(int id) {
_slaveid = id;
}
/**
* Build up a Modbus/TCP Connection
* @return If A Connection Is Successfully Built
*/
bool modbus::modbus_connect() {
if(HOST.empty() || PORT == 0) {
std::cout << "Missing Host and Port" << std::endl;
return false;
} else {
std::cout << "Found Proper Host "<< HOST << " and Port " <<PORT <<std::endl;
}
_socket = socket(AF_INET, SOCK_STREAM, 0);
if(_socket == -1) {
std::cout <<"Error Opening Socket" <<std::endl;
return false;
} else {
std::cout <<"Socket Opened Successfully" << std::endl;
}
struct timeval timeout{};
timeout.tv_sec = 20; // after 20 seconds connect() will timeout
timeout.tv_usec = 0;
setsockopt(_socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
setsockopt(_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
_server.sin_family = AF_INET;
_server.sin_addr.s_addr = inet_addr(HOST.c_str());
_server.sin_port = htons(PORT);
if (connect(_socket, (struct sockaddr*)&_server, sizeof(_server)) < 0) {
std::cout<< "Connection Error" << std::endl;
return false;
}
std::cout<< "Connected" <<std::endl;
_connected = true;
return true;
}
/**
* Close the Modbus/TCP Connection
*/
void modbus::modbus_close() const {
close(_socket);
std::cout <<"Socket Closed" <<std::endl;
}
/**
* Modbus Request Builder
* @param to_send Message Buffer to Be Sent
* @param address Reference Address
* @param func Modbus Functional Code
*/
void modbus::modbus_build_request(uint8_t *to_send, uint address, int func) const {
to_send[0] = (uint8_t) _msg_id >> 8u;
to_send[1] = (uint8_t) (_msg_id & 0x00FFu);
to_send[2] = 0;
to_send[3] = 0;
to_send[4] = 0;
to_send[6] = (uint8_t) _slaveid;
to_send[7] = (uint8_t) func;
to_send[8] = (uint8_t) (address >> 8u);
to_send[9] = (uint8_t) (address & 0x00FFu);
}
/**
* Write Request Builder and Sender
* @param address Reference Address
* @param amount Amount of data to be Written
* @param func Modbus Functional Code
* @param value Data to Be Written
*/
int modbus::modbus_write(int address, uint amount, int func, const uint16_t *value) {
int status = 0;
if(func == WRITE_COIL || func == WRITE_REG) {
uint8_t to_send[12];
modbus_build_request(to_send, address, func);
to_send[5] = 6;
to_send[10] = (uint8_t) (value[0] >> 8u);
to_send[11] = (uint8_t) (value[0] & 0x00FFu);
status = modbus_send(to_send, 12);
} else if(func == WRITE_REGS){
uint8_t to_send[13 + 2 * amount];
modbus_build_request(to_send, address, func);
to_send[5] = (uint8_t) (7 + 2 * amount);
to_send[10] = (uint8_t) (amount >> 8u);
to_send[11] = (uint8_t) (amount & 0x00FFu);
to_send[12] = (uint8_t) (2 * amount);
for(int i = 0; i < amount; i++) {
to_send[13 + 2 * i] = (uint8_t) (value[i] >> 8u);
to_send[14 + 2 * i] = (uint8_t) (value[i] & 0x00FFu);
}
status = modbus_send(to_send, 13 + 2 * amount);
} else if(func == WRITE_COILS) {
uint8_t to_send[14 + (amount -1) / 8 ];
modbus_build_request(to_send, address, func);
to_send[5] = (uint8_t) (7 + (amount + 7) / 8);
to_send[10] = (uint8_t) (amount >> 8u);
to_send[11] = (uint8_t) (amount & 0x00FFu);
to_send[12] = (uint8_t) ((amount + 7) / 8);
for(int i = 0; i < (amount+7)/8; i++)
to_send[13 + i] = 0; // init needed before summing!
for(int i = 0; i < amount; i++) {
to_send[13 + i/8] += (uint8_t) (value[i] << (i % 8u));
}
status = modbus_send(to_send, 14 + (amount - 1) / 8);
}
return status;
}
/**
* Read Request Builder and Sender
* @param address Reference Address
* @param amount Amount of Data to Read
* @param func Modbus Functional Code
*/
int modbus::modbus_read(int address, uint amount, int func){
uint8_t to_send[12];
modbus_build_request(to_send, address, func);
to_send[5] = 6;
to_send[10] = (uint8_t) (amount >> 8u);
to_send[11] = (uint8_t) (amount & 0x00FFu);
return modbus_send(to_send, 12);
}
/**
* Read Holding Registers
* MODBUS FUNCTION 0x03
* @param address Reference Address
* @param amount Amount of Registers to Read
* @param buffer Buffer to Store Data Read from Registers
*/
int modbus::modbus_read_holding_registers(int address, int amount, uint16_t *buffer) {
if(_connected) {
if(amount > 65535 || address > 65535) {
set_bad_input();
return EX_BAD_DATA;
}
modbus_read(address, amount, READ_REGS);
uint8_t to_rec[MAX_MSG_LENGTH];
ssize_t k = modbus_receive(to_rec);
if (k == -1) {
set_bad_con();
return BAD_CON;
}
modbuserror_handle(to_rec, READ_REGS);
if(err) return err_no;
for(uint i = 0; i < amount; i++) {
buffer[i] = ((uint16_t)to_rec[9u + 2u * i]) << 8u;
buffer[i] += (uint16_t) to_rec[10u + 2u * i];
}
return 0;
} else {
set_bad_con();
return BAD_CON;
}
}
/**
* Read Input Registers
* MODBUS FUNCTION 0x04
* @param address Reference Address
* @param amount Amount of Registers to Read
* @param buffer Buffer to Store Data Read from Registers
*/
int modbus::modbus_read_input_registers(int address, int amount, uint16_t *buffer) {
if(_connected){
if(amount > 65535 || address > 65535) {
set_bad_input();
return EX_BAD_DATA;
}
modbus_read(address, amount, READ_INPUT_REGS);
uint8_t to_rec[MAX_MSG_LENGTH];
ssize_t k = modbus_receive(to_rec);
if (k == -1) {
set_bad_con();
return BAD_CON;
}
modbuserror_handle(to_rec, READ_INPUT_REGS);
if(err) return err_no;
for(uint i = 0; i < amount; i++) {
buffer[i] = ((uint16_t)to_rec[9u + 2u * i]) << 8u;
buffer[i] += (uint16_t) to_rec[10u + 2u * i];
}
return 0;
} else {
set_bad_con();
return BAD_CON;
}
}
/**
* Read Coils
* MODBUS FUNCTION 0x01
* @param address Reference Address
* @param amount Amount of Coils to Read
* @param buffer Buffer to Store Data Read from Coils
*/
int modbus::modbus_read_coils(int address, int amount, bool *buffer) {
if(_connected) {
if(amount > 2040 || address > 65535) {
set_bad_input();
return EX_BAD_DATA;
}
modbus_read(address, amount, READ_COILS);
uint8_t to_rec[MAX_MSG_LENGTH];
ssize_t k = modbus_receive(to_rec);
if (k == -1) {
set_bad_con();
return BAD_CON;
}
modbuserror_handle(to_rec, READ_COILS);
if(err) return err_no;
for(uint i = 0; i < amount; i++) {
buffer[i] = (bool) ((to_rec[9u + i / 8u] >> (i % 8u)) & 1u);
}
return 0;
} else {
set_bad_con();
return BAD_CON;
}
}
/**
* Read Input Bits(Discrete Data)
* MODBUS FUNCITON 0x02
* @param address Reference Address
* @param amount Amount of Bits to Read
* @param buffer Buffer to store Data Read from Input Bits
*/
int modbus::modbus_read_input_bits(int address, int amount, bool* buffer) {
if(_connected) {
if(amount > 2040 || address > 65535) {
set_bad_input();
return EX_BAD_DATA;
}
modbus_read(address, amount, READ_INPUT_BITS);
uint8_t to_rec[MAX_MSG_LENGTH];
ssize_t k = modbus_receive(to_rec);
if (k == -1) {
set_bad_con();
return BAD_CON;
}
if(err) return err_no;
for(uint i = 0; i < amount; i++) {
buffer[i] = (bool) ((to_rec[9u + i / 8u] >> (i % 8u)) & 1u);
}
modbuserror_handle(to_rec, READ_INPUT_BITS);
return 0;
} else {
return BAD_CON;
}
}
/**
* Write Single Coils
* MODBUS FUNCTION 0x05
* @param address Reference Address
* @param to_write Value to be Written to Coil
*/
int modbus::modbus_write_coil(int address, const bool& to_write) {
if(_connected) {
if(address > 65535) {
set_bad_input();
return EX_BAD_DATA;
}
int value = to_write * 0xFF00;
modbus_write(address, 1, WRITE_COIL, (uint16_t *)&value);
uint8_t to_rec[MAX_MSG_LENGTH];
ssize_t k = modbus_receive(to_rec);
if (k == -1) {
set_bad_con();
return BAD_CON;
}
modbuserror_handle(to_rec, WRITE_COIL);
if(err) return err_no;
return 0;
} else {
set_bad_con();
return BAD_CON;
}
}
/**
* Write Single Register
* FUCTION 0x06
* @param address Reference Address
* @param value Value to Be Written to Register
*/
int modbus::modbus_write_register(int address, const uint16_t& value) {
if(_connected) {
if(address > 65535) {
set_bad_input();
return EX_BAD_DATA;
}
modbus_write(address, 1, WRITE_REG, &value);
uint8_t to_rec[MAX_MSG_LENGTH];
ssize_t k = modbus_receive(to_rec);
if (k == -1) {
set_bad_con();
return BAD_CON;
}
modbuserror_handle(to_rec, WRITE_COIL);
if(err) return err_no;
return 0;
} else {
set_bad_con();
return BAD_CON;
}
}
/**
* Write Multiple Coils
* MODBUS FUNCTION 0x0F
* @param address Reference Address
* @param amount Amount of Coils to Write
* @param value Values to Be Written to Coils
*/
int modbus::modbus_write_coils(int address, int amount, const bool *value) {
if(_connected) {
if(address > 65535 || amount > 65535) {
set_bad_input();
return EX_BAD_DATA;
}
uint16_t temp[amount];
for(int i = 0; i < amount; i++) {
temp[i] = (uint16_t)value[i];
}
modbus_write(address, amount, WRITE_COILS, temp);
uint8_t to_rec[MAX_MSG_LENGTH];
ssize_t k = modbus_receive(to_rec);
if (k == -1) {
set_bad_con();
return BAD_CON;
}
modbuserror_handle(to_rec, WRITE_COILS);
if(err) return err_no;
return 0;
} else {
set_bad_con();
return BAD_CON;
}
}
/**
* Write Multiple Registers
* MODBUS FUNCION 0x10
* @param address Reference Address
* @param amount Amount of Value to Write
* @param value Values to Be Written to the Registers
*/
int modbus::modbus_write_registers(int address, int amount, const uint16_t *value) {
if(_connected) {
if(address > 65535 || amount > 65535) {
set_bad_input();
return EX_BAD_DATA;
}
modbus_write(address, amount, WRITE_REGS, value);
uint8_t to_rec[MAX_MSG_LENGTH];
ssize_t k = modbus_receive(to_rec);
if (k == -1) {
set_bad_con();
return BAD_CON;
}
modbuserror_handle(to_rec, WRITE_REGS);
if(err) return err_no;
return 0;
} else {
set_bad_con();
return BAD_CON;
}
}
/**
* Data Sender
* @param to_send Request to Be Sent to Server
* @param length Length of the Request
* @return Size of the request
*/
ssize_t modbus::modbus_send(uint8_t *to_send, int length) {
_msg_id++;
return send(_socket, to_send, (size_t)length, 0);
}
/**
* Data Receiver
* @param buffer Buffer to Store the Data Retrieved
* @return Size of Incoming Data
*/
ssize_t modbus::modbus_receive(uint8_t *buffer) const {
return recv(_socket, (char *) buffer, 1024, 0);
}
void modbus::set_bad_con() {
err = true;
error_msg = "BAD CONNECTION";
}
void modbus::set_bad_input() {
err = true;
error_msg = "BAD FUNCTION INPUT";
}
/**
* Error Code Handler
* @param msg Message Received from the Server
* @param func Modbus Functional Code
*/
void modbus::modbuserror_handle(const uint8_t *msg, int func) {
if(msg[7] == func + 0x80) {
err = true;
switch(msg[8]){
case EX_ILLEGAL_FUNCTION:
error_msg = "1 Illegal Function";
break;
case EX_ILLEGAL_ADDRESS:
error_msg = "2 Illegal Address";
break;
case EX_ILLEGAL_VALUE:
error_msg = "3 Illegal Value";
break;
case EX_SERVER_FAILURE:
error_msg = "4 Server Failure";
break;
case EX_ACKNOWLEDGE:
error_msg = "5 Acknowledge";
break;
case EX_SERVER_BUSY:
error_msg = "6 Server Busy";
break;
case EX_NEGATIVE_ACK:
error_msg = "7 Negative Acknowledge";
break;
case EX_MEM_PARITY_PROB:
error_msg = "8 Memory Parity Problem";
break;
case EX_GATEWAY_PROBLEMP:
error_msg = "10 Gateway Path Unavailable";
break;
case EX_GATEWYA_PROBLEMF:
error_msg = "11 Gateway Target Device Failed to Respond";
break;
default:
error_msg = "UNK";
break;
}
}
err = false;
error_msg = "NO ERR";
}
#endif //MODBUSPP_MODBUS_H