random-test-server.c
Go to the documentation of this file.
1 /*
2  * Copyright © 2008-2010 Stéphane Raimbault <stephane.raimbault@gmail.com>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include <stdio.h>
19 #include <unistd.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 
23 #include <modbus.h>
24 
25 int main(void)
26 {
27  int socket;
28  modbus_t *ctx;
30 
31  ctx = modbus_new_tcp("127.0.0.1", 1502);
32  /* modbus_set_debug(ctx, TRUE); */
33 
34  mb_mapping = modbus_mapping_new(500, 500, 500, 500);
35  if (mb_mapping == NULL) {
36  fprintf(stderr, "Failed to allocate the mapping: %s\n",
37  modbus_strerror(errno));
38  modbus_free(ctx);
39  return -1;
40  }
41 
42  socket = modbus_tcp_listen(ctx, 1);
43  modbus_tcp_accept(ctx, &socket);
44 
45  for (;;) {
46  uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
47  int rc;
48 
49  rc = modbus_receive(ctx, query);
50  if (rc != -1) {
51  /* rc is the query size */
52  modbus_reply(ctx, query, rc, mb_mapping);
53  } else {
54  /* Connection closed by the client or error */
55  break;
56  }
57  }
58 
59  printf("Quit the loop: %s\n", modbus_strerror(errno));
60 
61  modbus_mapping_free(mb_mapping);
62  modbus_close(ctx);
63  modbus_free(ctx);
64 
65  return 0;
66 }
modbus_mapping_t * modbus_mapping_new(int nb_coil_status, int nb_input_status, int nb_holding_registers, int nb_input_registers)
Definition: modbus.c:1547
int modbus_receive(modbus_t *ctx, uint8_t *req)
Definition: modbus.c:460
#define MODBUS_TCP_MAX_ADU_LENGTH
Definition: modbus-tcp.h:41
void modbus_free(modbus_t *ctx)
Definition: modbus.c:1528
void modbus_close(modbus_t *ctx)
Definition: modbus.c:1520
int main(void)
int modbus_reply(modbus_t *ctx, const uint8_t *req, int req_length, modbus_mapping_t *mb_mapping)
Definition: modbus.c:641
int modbus_tcp_accept(modbus_t *ctx, int *socket)
Definition: modbus-tcp.c:524
int modbus_tcp_listen(modbus_t *ctx, int nb_connection)
Definition: modbus-tcp.c:387
modbus_t * ctx
const char * modbus_strerror(int errnum)
Definition: modbus.c:53
void modbus_mapping_free(modbus_mapping_t *mb_mapping)
Definition: modbus.c:1625
modbus_mapping_t * mb_mapping
modbus_t * modbus_new_tcp(const char *ip_address, int port)
Definition: modbus-tcp.c:636


libmodbus
Author(s):
autogenerated on Sat Nov 21 2020 03:17:32