* Copyright (c) 2002,2016 Mario de Sousa (msousa@fe.up.pt)
* This file is part of the Modbus library for Beremiz and matiec.
* This Modbus library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this Modbus library. If not, see <http://www.gnu.org/licenses/>.
* This code is made available on the understanding that it will not be
* used in safety-critical situations without a full and competent review.
#include <fcntl.h> /* File control definitions */
#include <stdio.h> /* Standard input/output */
#include <termio.h> /* POSIX terminal control definitions */
#include <sys/time.h> /* Time structures for select() */
#include <unistd.h> /* POSIX Symbolic Constants */
#include <errno.h> /* Error definitions */
#include "mb_slave_private.h"
#include "mb_master_private.h"
//#define DEBUG /* uncomment to see the data sent and received */
layer1_funct_ptr_t fptr_[4] = {
{ /* WARNING: TCP functions MUST be the first, as we have this hardcoded in the code! */
/* more specifically, in the get_ttyfd() macro in mb_slave.c */
/* in the mb_slave_new() function in mb_slave.c */
/* in the mb_master_connect() function in mb_master.c */
,&modbus_tcp_silence_init
,&modbus_tcp_get_min_timeout
,&modbus_rtu_silence_init
,&modbus_rtu_get_min_timeout
,&modbus_ascii_silence_init
,&modbus_ascii_get_min_timeout
NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
/************************************************************************
initialise / shutdown the library
These functions sets up/shut down the library state
(allocate memory for buffers, initialise data strcutures, etc)
**************************************************************************/
#define max(a,b) (((a)>(b))?(a):(b))
int mb_slave_and_master_init(int nd_count_tcp, int nd_count_rtu, int nd_count_ascii) {
fprintf( stderr, "mb_slave_and_master_init()\n");
fprintf( stderr, "creating %d nodes\n", nd_count);
/* initialise layer 1 library */
if (modbus_tcp_init (nd_count_tcp, DEF_OPTIMIZATION) < 0) goto error_exit_0;
if (modbus_rtu_init (nd_count_rtu, DEF_OPTIMIZATION) < 0) goto error_exit_1;
if (modbus_ascii_init(nd_count_ascii, DEF_OPTIMIZATION) < 0) goto error_exit_2;
/* initialise master and slave libraries... */
if (mb_slave_init__ () < 0) goto error_exit_3;
if (mb_master_init__() < 0) goto error_exit_4;
int mb_slave_and_master_done(void) {
res |= mb_slave_done__ ();
res |= mb_master_done__ ();
res |= modbus_ascii_done();
res |= modbus_rtu_done ();
res |= modbus_tcp_done ();