-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommservice.cpp
More file actions
96 lines (67 loc) · 2.1 KB
/
commservice.cpp
File metadata and controls
96 lines (67 loc) · 2.1 KB
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
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include "modbus.h"
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}
void *modbustcp(void *slaveid)
{
int sid;
sid = (long)slaveid;
// create a modbus object
modbus mb = modbus("127.0.0.1", 502);
// set slave id
cout<<"connected to ";
cout<<sid;
mb.modbus_set_slave_id(sid);
// connect with the server
mb.modbus_connect();
// read coil function 0x01
bool read_coil;
mb.modbus_read_coils(0, 1, &read_coil);
cout<<read_coil;
cout<<"\n";
// read input bits(discrete input) function 0x02
bool read_bits;
mb.modbus_read_input_bits(0, 1, &read_bits);
// read holding registers function 0x03
uint16_t read_holding_regs[1];
mb.modbus_read_holding_registers(0, 1, read_holding_regs);
cout<<read_holding_regs[0];
// read input registers function 0x04
uint16_t read_input_regs[1];
mb.modbus_read_input_registers(0, 1, read_input_regs);
// write single coil function 0x05
mb.modbus_write_coil(0, true);
// write single reg function 0x06
mb.modbus_write_register(0, 123);
// write multiple coils function 0x0F
bool write_cols[4] = {true, true, true, true};
mb.modbus_write_coils(0,4,write_cols);
// write multiple regs function 0x10
uint16_t write_regs[4] = {123, 123, 123};
mb.modbus_write_registers(0, 4, write_regs);
// close connection and free the memory
mb.modbus_close();
//delete(&mb);
}
int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, modbustcp, (void *)i);
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}