-
Notifications
You must be signed in to change notification settings - Fork 0
/
modbusD.h
111 lines (95 loc) · 2.65 KB
/
modbusD.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
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#define port 2222
int Send_Modbus_request (fd, APDU, APDUlen, APDU_R){
int rd;
// generates TI (trans.ID sequence number)
PDU = APDU(SDU) + MBAP
write (fd, PDU, PDUlen) // sends Modbus TCP PDU
rd = read (fd, PDU_R, PDU_Rlen);
if(rd <0){
printf("Erro");
exit(1);
}
if(rd>0){
printf("Mensagem recebida: %s\n", APDU_R);
gets(APDU_R);
puts("A escrever: ");
send(sock, APDU_R, 1024, 0);
}
//if response, remove MBAP, PDU_R APDU_R
// returns: APDU_R and 0 – ok, <0 – error (timeout)
}
//////////////////////////////////////
while(!STOP){
printf("\nWrite something\n ");
//scanf("%s", buf);
fgets (buf, BUF_LEN, stdin);
/* Remove trailing newline, if there. */
if ((strlen(buf)>0) && (buf[strlen (buf) - 1] == '\n'))
buf[strlen (buf) - 1] = '\0';
len=send(sock, buf, strlen(buf)+1, 0);
if(len!=strlen(buf)+1) printf("\nSEND ERROR\n");
printf("\nSent:%d\n\n",len);
/*Check if it's terminating char*/
if (buf[0]=='#'){
printf("\nTERMINATING CHAR SENT\n");
STOP=1;
continue;
}
recv(sock, buf_in, BUF_LEN,0);
if(len==-1){
printf("RECV ERROR\n");
continue;
}
printf("Received data:\n %s \n Size: %d\n",buf_in,len);
}
///////////////////////////////////////
int Receive_Modbus_request (fd, APDU){
read (fd, PDU(MBAP), 7 ) // read MBAP of request PDU
//remove MBAP: TI and length (APDUlen + 1)
read (fd, APDU, APDUlen) // read request APDU
// returns: APDU and TI – ok, <0 – erro
}
//////////////////////////////////
while(!STOP){
len=recv(sd, buf, BUF_LEN, 0);
if(len==-1){
printf("RECV ERROR\n");
STOP=1;
continue;
}
printf("Received data:\n %s\n Size: %d\n",buf,len);
if(buf[0]=='#'){
printf("\nTERMINATING CHAR RECEIVED\n");
STOP=1;
continue;
}
for(i=0;i<strlen(buf);i++){
if(buf[i]>='a' && buf[i]<='z'){
buf[i]=(char)(buf[i]-32);
}
}
send(sd,buf,len,0);
if(len!=strlen(buf)+1) printf("SEND ERROR\n");
printf("\nSent:%d\n\n",len);
}
////////////////////////////////
int Send_Modbus_response (fd, APDU_R, APDU_Rlen, TI){
// assembles PDU = APDU_R + MBAP (with TI)
write (fd, PDU, PDUlen)//sends ModbusTCP response PDU // returns: >0 – ok, <0 – erro
}
int R_coils (st, n, val){
// read n regs/ coils starting from st and write in val
// returns: num regs/coils read, values in val – ok, <0 – error
}
int W_coils (st, n, val){
// write n regs/ coils starting from st using values from val
// returns: num regs/ coils written – ok, <0 – error
}