hlp:荆州版本

This commit is contained in:
kite_lucs
2026-10-19 17:03:47 +08:00
parent e533ea8e0b
commit 065b146998
438 changed files with 163143 additions and 185387 deletions
+81 -81
View File
@@ -1,81 +1,81 @@
/*
* FreeModbus Libary: BSD Socket Library Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: port.h,v 1.1 2007/09/12 10:15:56 wolti Exp $
*/
/**********************************************************
* Linux TCP support.
* Based on Walter's project.
* Modified by Steven Guo <gotop167@163.com>
***********************************************************/
#ifndef _PORT_H
#define _PORT_H
#include <assert.h>
#define INLINE
#define PR_BEGIN_EXTERN_C extern "C" {
#define PR_END_EXTERN_C }
#ifdef __cplusplus
PR_BEGIN_EXTERN_C
#endif
/* ----------------------- Defines ------------------------------------------*/
#define ENTER_CRITICAL_SECTION( )
#define EXIT_CRITICAL_SECTION( )
#define MB_PORT_HAS_CLOSE 1
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
/* ----------------------- Type definitions ---------------------------------*/
typedef int SOCKET;
#define SOCKET_ERROR (-1)
#define INVALID_SOCKET (~0)
typedef char BOOL;
typedef unsigned char UCHAR;
typedef unsigned char BYTE;
typedef char CHAR;
typedef unsigned short USHORT;
typedef short SHORT;
typedef unsigned long ULONG;
typedef long LONG;
typedef enum
{
MB_LOG_DEBUG,
MB_LOG_INFO,
MB_LOG_WARN,
MB_LOG_ERROR
} eMBPortLogLevel;
/* ----------------------- Function prototypes ------------------------------*/
void TcpvMBPortLog( eMBPortLogLevel eLevel, const CHAR * szModule, const CHAR * szFmt,
... );
#ifdef __cplusplus
PR_END_EXTERN_C
#endif
#endif
/*
* FreeModbus Libary: BSD Socket Library Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: port.h,v 1.1 2007/09/12 10:15:56 wolti Exp $
*/
/**********************************************************
* Linux TCP support.
* Based on Walter's project.
* Modified by Steven Guo <gotop167@163.com>
***********************************************************/
#ifndef _PORT_H
#define _PORT_H
#include <assert.h>
#define INLINE
#define PR_BEGIN_EXTERN_C extern "C" {
#define PR_END_EXTERN_C }
#ifdef __cplusplus
PR_BEGIN_EXTERN_C
#endif
/* ----------------------- Defines ------------------------------------------*/
#define ENTER_CRITICAL_SECTION( )
#define EXIT_CRITICAL_SECTION( )
#define MB_PORT_HAS_CLOSE 1
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
/* ----------------------- Type definitions ---------------------------------*/
typedef int SOCKET;
#define SOCKET_ERROR (-1)
#define INVALID_SOCKET (~0)
typedef char BOOL;
typedef unsigned char UCHAR;
typedef unsigned char BYTE;
typedef char CHAR;
typedef unsigned short USHORT;
typedef short SHORT;
typedef unsigned long ULONG;
typedef long LONG;
typedef enum
{
MB_LOG_DEBUG,
MB_LOG_INFO,
MB_LOG_WARN,
MB_LOG_ERROR
} eMBPortLogLevel;
/* ----------------------- Function prototypes ------------------------------*/
void TcpvMBPortLog( eMBPortLogLevel eLevel, const CHAR * szModule, const CHAR * szFmt,
... );
#ifdef __cplusplus
PR_END_EXTERN_C
#endif
#endif
+72 -72
View File
@@ -1,72 +1,72 @@
/*
* FreeModbus Libary: Win32 Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: portevent.c,v 1.1 2007/09/12 10:15:56 wolti Exp $
*/
/**********************************************************
* Linux TCP support.
* Based on Walter's project.
* Modified by Steven Guo <gotop167@163.com>
***********************************************************/
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
/* ----------------------- Variables ----------------------------------------*/
static eMBEventType eQueuedEvent;
static BOOL xEventInQueue;
/* ----------------------- Function prototypes ------------------------------*/
BOOL xMBPortTCPPool( void );
/* ----------------------- Start implementation -----------------------------*/
BOOL
xMBPortEventInit( void )
{
xEventInQueue = FALSE;
return TRUE;
}
BOOL
xMBPortEventPost( eMBEventType eEvent )
{
xEventInQueue = TRUE;
eQueuedEvent = eEvent;
return TRUE;
}
BOOL
xMBPortEventGet( eMBEventType * eEvent )
{
BOOL xEventHappened = FALSE;
if( xEventInQueue )
{
*eEvent = eQueuedEvent;
xEventInQueue = FALSE;
xEventHappened = TRUE;
}
else
{
/* We can't do anything with errors from the pooling module. */
( void )xMBPortTCPPool( );
}
return xEventHappened;
}
/*
* FreeModbus Libary: Win32 Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: portevent.c,v 1.1 2007/09/12 10:15:56 wolti Exp $
*/
/**********************************************************
* Linux TCP support.
* Based on Walter's project.
* Modified by Steven Guo <gotop167@163.com>
***********************************************************/
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
/* ----------------------- Variables ----------------------------------------*/
static eMBEventType eQueuedEvent;
static BOOL xEventInQueue;
/* ----------------------- Function prototypes ------------------------------*/
BOOL xMBPortTCPPool( void );
/* ----------------------- Start implementation -----------------------------*/
BOOL
xMBPortEventInit( void )
{
xEventInQueue = FALSE;
return TRUE;
}
BOOL
xMBPortEventPost( eMBEventType eEvent )
{
xEventInQueue = TRUE;
eQueuedEvent = eEvent;
return TRUE;
}
BOOL
xMBPortEventGet( eMBEventType * eEvent )
{
BOOL xEventHappened = FALSE;
if( xEventInQueue )
{
*eEvent = eQueuedEvent;
xEventInQueue = FALSE;
xEventHappened = TRUE;
}
else
{
/* We can't do anything with errors from the pooling module. */
( void )xMBPortTCPPool( );
}
return xEventHappened;
}
+69 -69
View File
@@ -1,69 +1,69 @@
/*
* FreeModbus Libary: Win32 Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: portother.c,v 1.1 2007/09/12 10:15:56 wolti Exp $
*/
/**********************************************************
* Linux TCP support.
* Based on Walter's project.
* Modified by Steven Guo <gotop167@163.com>
***********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
#include "mbconfig.h"
BOOL
prvMBTCPPortAddressToString( SOCKET xSocket, CHAR * szAddr, USHORT usBufSize )
{
return TRUE;
}
CHAR *
prvMBTCPPortFrameToString( UCHAR * pucFrame, USHORT usFrameLen )
{
return NULL;
}
CHAR *
WsaError2String( int iError )
{
return NULL;
}
void
vMBPortLog( eMBPortLogLevel eLevel, const CHAR * szModule, const CHAR * szFmt, ... )
{
va_list args;
static const CHAR *arszLevel2Str[] = { "DEBUG", "INFO", "WARN", "ERROR" };
fprintf( stderr, "%s: %s: ", arszLevel2Str[eLevel], szModule );
va_start( args, szFmt );
fprintf( stderr, szFmt, args );
va_end( args );
}
/*
* FreeModbus Libary: Win32 Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: portother.c,v 1.1 2007/09/12 10:15:56 wolti Exp $
*/
/**********************************************************
* Linux TCP support.
* Based on Walter's project.
* Modified by Steven Guo <gotop167@163.com>
***********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
#include "mbconfig.h"
BOOL
prvMBTCPPortAddressToString( SOCKET xSocket, CHAR * szAddr, USHORT usBufSize )
{
return TRUE;
}
CHAR *
prvMBTCPPortFrameToString( UCHAR * pucFrame, USHORT usFrameLen )
{
return NULL;
}
CHAR *
WsaError2String( int iError )
{
return NULL;
}
void
vMBPortLog( eMBPortLogLevel eLevel, const CHAR * szModule, const CHAR * szFmt, ... )
{
va_list args;
static const CHAR *arszLevel2Str[] = { "DEBUG", "INFO", "WARN", "ERROR" };
fprintf( stderr, "%s: %s: ", arszLevel2Str[eLevel], szModule );
va_start( args, szFmt );
fprintf( stderr, szFmt, args );
va_end( args );
}
+364 -364
View File
@@ -1,364 +1,364 @@
/*
* FreeModbus Libary: Linux Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: portserial.c,v 1.3 2006/10/12 08:35:34 wolti Exp $
*/
/* ----------------------- Standard includes --------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
#include "mbconfig.h"
/* ----------------------- Defines -----------------------------------------*/
#if MB_ASCII_ENABLED == 1
#define BUF_SIZE 513 /* must hold a complete ASCII frame. */
#else
#define BUF_SIZE 256 /* must hold a complete RTU frame. */
#endif
/* ----------------------- Static variables ---------------------------------*/
static int iSerialFd = -1;
static BOOL bRxEnabled;
static BOOL bTxEnabled;
static ULONG ulTimeoutMs;
static UCHAR ucBuffer[BUF_SIZE];
static int uiRxBufferPos;
static int uiTxBufferPos;
static struct termios xOldTIO;
/* ----------------------- Function prototypes ------------------------------*/
static BOOL prvbMBPortSerialRead( UCHAR * pucBuffer, USHORT usNBytes, USHORT * usNBytesRead );
static BOOL prvbMBPortSerialWrite( UCHAR * pucBuffer, USHORT usNBytes );
/* ----------------------- Begin implementation -----------------------------*/
void
vMBPortSerialEnable( BOOL bEnableRx, BOOL bEnableTx )
{
/* it is not allowed that both receiver and transmitter are enabled. */
assert( !bEnableRx || !bEnableTx );
if( bEnableRx )
{
( void )tcflush( iSerialFd, TCIFLUSH );
uiRxBufferPos = 0;
bRxEnabled = TRUE;
}
else
{
bRxEnabled = FALSE;
}
if( bEnableTx )
{
bTxEnabled = TRUE;
uiTxBufferPos = 0;
}
else
{
bTxEnabled = FALSE;
}
}
BOOL
xMBPortSerialInit( UCHAR ucPort, ULONG ulBaudRate, UCHAR ucDataBits, eMBParity eParity )
{
CHAR szDevice[16];
BOOL bStatus = TRUE;
struct termios xNewTIO;
speed_t xNewSpeed;
//snprintf( szDevice, 16, "/dev/ttyUSB%d", ucPort );
snprintf( szDevice, 16, "/dev/ttyO1");
if( ( iSerialFd = open( szDevice, O_RDWR | O_NOCTTY ) ) < 0 )
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't open serial port %s: %s\n", szDevice,
strerror( errno ) );
bStatus = FALSE;
return bStatus;
}
else if( tcgetattr( iSerialFd, &xOldTIO ) != 0 )
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't get settings from port %s: %s\n", szDevice,
strerror( errno ) );
}
else
{
bzero( &xNewTIO, sizeof( struct termios ) );
xNewTIO.c_iflag |= IGNBRK | INPCK;
xNewTIO.c_cflag |= CREAD | CLOCAL;
switch ( eParity )
{
case MB_PAR_NONE:
break;
case MB_PAR_EVEN:
xNewTIO.c_cflag |= PARENB;
break;
case MB_PAR_ODD:
xNewTIO.c_cflag |= PARENB | PARODD;
break;
default:
bStatus = FALSE;
}
switch ( ucDataBits )
{
case 8:
xNewTIO.c_cflag |= CS8;
break;
case 7:
xNewTIO.c_cflag |= CS7;
break;
default:
bStatus = FALSE;
}
switch ( ulBaudRate )
{
case 9600:
xNewSpeed = B9600;
break;
case 19200:
xNewSpeed = B19200;
break;
case 38400:
xNewSpeed = B38400;
break;
case 57600:
xNewSpeed = B57600;
break;
case 115200:
xNewSpeed = B115200;
break;
default:
bStatus = FALSE;
}
/*设置等待时间和最小接收字符*/
xNewTIO.c_cc[VTIME] = 0;
xNewTIO.c_cc[VMIN] = 0;
/*处理未接收字符*/
tcflush(iSerialFd,TCIFLUSH); //lch add
if( bStatus )
{
if( cfsetispeed( &xNewTIO, xNewSpeed ) != 0 )
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't set baud rate %ld for port %s: %s\n",
ulBaudRate, strerror( errno ) );
}
else if( cfsetospeed( &xNewTIO, xNewSpeed ) != 0 )
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't set baud rate %ld for port %s: %s\n",
ulBaudRate, szDevice, strerror( errno ) );
}
else if( tcsetattr( iSerialFd, TCSANOW, &xNewTIO ) != 0 )
//else if( tcsetattr( iSerialFd, TCSAFLUSH, &xNewTIO ) != 0 ) //lch fix
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't set settings for port %s: %s\n",
szDevice, strerror( errno ) );
}
else
{
vMBPortSerialEnable( FALSE, FALSE );
bStatus = TRUE;
}
}
}
return bStatus;
}
BOOL
xMBPortSerialSetTimeout( ULONG ulNewTimeoutMs )
{
if( ulNewTimeoutMs > 0 )
{
ulTimeoutMs = ulNewTimeoutMs;
}
else
{
ulTimeoutMs = 1;
}
return TRUE;
}
void
vMBPortClose( void )
{
if( iSerialFd != -1 )
{
( void )tcsetattr( iSerialFd, TCSANOW, &xOldTIO );
( void )close( iSerialFd );
iSerialFd = -1;
}
}
BOOL
prvbMBPortSerialRead( UCHAR * pucBuffer, USHORT usNBytes, USHORT * usNBytesRead )
{
BOOL bResult = TRUE;
ssize_t res;
fd_set rfds;
struct timeval tv;
// tv.tv_sec = 1;
// tv.tv_usec = 60000;
tv.tv_sec = 0;
tv.tv_usec = 10000; //lch fix
FD_ZERO( &rfds );
FD_SET( iSerialFd, &rfds );
/* Wait until character received or timeout. Recover in case of an
* interrupted read system call. */
do
{
if( select( iSerialFd + 1, &rfds, NULL, NULL, &tv ) == -1 )
{
if( errno != EINTR )
{
bResult = FALSE;
}
}
else if( FD_ISSET( iSerialFd, &rfds ) )
{
if( ( res = read( iSerialFd, pucBuffer, usNBytes ) ) == -1 )
{
bResult = FALSE;
}
else
{
*usNBytesRead = ( USHORT ) res;
break;
}
}
else
{
*usNBytesRead = 0;
break;
}
}
while( bResult == TRUE );
return bResult;
}
BOOL
prvbMBPortSerialWrite( UCHAR * pucBuffer, USHORT usNBytes )
{
ssize_t res;
size_t left = ( size_t ) usNBytes;
size_t done = 0;
while( left > 0 )
{
if( ( res = write( iSerialFd, pucBuffer + done, left ) ) == -1 )
{
if( errno != EINTR )
{
break;
}
/* call write again because of interrupted system call. */
continue;
}
done += res;
left -= res;
}
return left == 0 ? TRUE : FALSE;
}
BOOL
xMBPortSerialPoll( )
{
BOOL bStatus = TRUE;
USHORT usBytesRead;
int i;
while( bRxEnabled )
{
if( prvbMBPortSerialRead( &ucBuffer[0], BUF_SIZE, &usBytesRead ) )
{
if( usBytesRead == 0 )
{
/* timeout with no bytes. */
break;
}
else if( usBytesRead > 0 )
{
for( i = 0; i < usBytesRead; i++ )
{
/* Call the modbus stack and let him fill the buffers. */
( void )pxMBFrameCBByteReceived( );
}
uiRxBufferPos = 0;
}
}
else
{
vMBPortLog( MB_LOG_ERROR, "SER-POLL", "read failed on serial device: %s\n",
strerror( errno ) );
bStatus = FALSE;
}
}
if( bTxEnabled )
{
while( bTxEnabled )
{
( void )pxMBFrameCBTransmitterEmpty( );
/* Call the modbus stack to let him fill the buffer. */
}
if( !prvbMBPortSerialWrite( &ucBuffer[0], uiTxBufferPos ) )
{
vMBPortLog( MB_LOG_ERROR, "SER-POLL", "write failed on serial device: %s\n",
strerror( errno ) );
bStatus = FALSE;
}
}
return bStatus;
}
BOOL
xMBPortSerialPutByte( CHAR ucByte )
{
assert( uiTxBufferPos < BUF_SIZE );
ucBuffer[uiTxBufferPos] = ucByte;
uiTxBufferPos++;
return TRUE;
}
BOOL
xMBPortSerialGetByte( CHAR * pucByte )
{
assert( uiRxBufferPos < BUF_SIZE );
*pucByte = ucBuffer[uiRxBufferPos];
uiRxBufferPos++;
return TRUE;
}
/*
* FreeModbus Libary: Linux Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: portserial.c,v 1.3 2006/10/12 08:35:34 wolti Exp $
*/
/* ----------------------- Standard includes --------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
#include "mbconfig.h"
/* ----------------------- Defines -----------------------------------------*/
#if MB_ASCII_ENABLED == 1
#define BUF_SIZE 513 /* must hold a complete ASCII frame. */
#else
#define BUF_SIZE 256 /* must hold a complete RTU frame. */
#endif
/* ----------------------- Static variables ---------------------------------*/
static int iSerialFd = -1;
static BOOL bRxEnabled;
static BOOL bTxEnabled;
static ULONG ulTimeoutMs;
static UCHAR ucBuffer[BUF_SIZE];
static int uiRxBufferPos;
static int uiTxBufferPos;
static struct termios xOldTIO;
/* ----------------------- Function prototypes ------------------------------*/
static BOOL prvbMBPortSerialRead( UCHAR * pucBuffer, USHORT usNBytes, USHORT * usNBytesRead );
static BOOL prvbMBPortSerialWrite( UCHAR * pucBuffer, USHORT usNBytes );
/* ----------------------- Begin implementation -----------------------------*/
void
vMBPortSerialEnable( BOOL bEnableRx, BOOL bEnableTx )
{
/* it is not allowed that both receiver and transmitter are enabled. */
assert( !bEnableRx || !bEnableTx );
if( bEnableRx )
{
( void )tcflush( iSerialFd, TCIFLUSH );
uiRxBufferPos = 0;
bRxEnabled = TRUE;
}
else
{
bRxEnabled = FALSE;
}
if( bEnableTx )
{
bTxEnabled = TRUE;
uiTxBufferPos = 0;
}
else
{
bTxEnabled = FALSE;
}
}
BOOL
xMBPortSerialInit( UCHAR ucPort, ULONG ulBaudRate, UCHAR ucDataBits, eMBParity eParity )
{
CHAR szDevice[16];
BOOL bStatus = TRUE;
struct termios xNewTIO;
speed_t xNewSpeed;
//snprintf( szDevice, 16, "/dev/ttyUSB%d", ucPort );
snprintf( szDevice, 16, "/dev/ttyO1");
if( ( iSerialFd = open( szDevice, O_RDWR | O_NOCTTY ) ) < 0 )
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't open serial port %s: %s\n", szDevice,
strerror( errno ) );
bStatus = FALSE;
return bStatus;
}
else if( tcgetattr( iSerialFd, &xOldTIO ) != 0 )
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't get settings from port %s: %s\n", szDevice,
strerror( errno ) );
}
else
{
bzero( &xNewTIO, sizeof( struct termios ) );
xNewTIO.c_iflag |= IGNBRK | INPCK;
xNewTIO.c_cflag |= CREAD | CLOCAL;
switch ( eParity )
{
case MB_PAR_NONE:
break;
case MB_PAR_EVEN:
xNewTIO.c_cflag |= PARENB;
break;
case MB_PAR_ODD:
xNewTIO.c_cflag |= PARENB | PARODD;
break;
default:
bStatus = FALSE;
}
switch ( ucDataBits )
{
case 8:
xNewTIO.c_cflag |= CS8;
break;
case 7:
xNewTIO.c_cflag |= CS7;
break;
default:
bStatus = FALSE;
}
switch ( ulBaudRate )
{
case 9600:
xNewSpeed = B9600;
break;
case 19200:
xNewSpeed = B19200;
break;
case 38400:
xNewSpeed = B38400;
break;
case 57600:
xNewSpeed = B57600;
break;
case 115200:
xNewSpeed = B115200;
break;
default:
bStatus = FALSE;
}
/*设置等待时间和最小接收字符*/
xNewTIO.c_cc[VTIME] = 0;
xNewTIO.c_cc[VMIN] = 0;
/*处理未接收字符*/
tcflush(iSerialFd,TCIFLUSH); //lch add
if( bStatus )
{
if( cfsetispeed( &xNewTIO, xNewSpeed ) != 0 )
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't set baud rate %ld for port %s: %s\n",
ulBaudRate, strerror( errno ) );
}
else if( cfsetospeed( &xNewTIO, xNewSpeed ) != 0 )
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't set baud rate %ld for port %s: %s\n",
ulBaudRate, szDevice, strerror( errno ) );
}
else if( tcsetattr( iSerialFd, TCSANOW, &xNewTIO ) != 0 )
//else if( tcsetattr( iSerialFd, TCSAFLUSH, &xNewTIO ) != 0 ) //lch fix
{
vMBPortLog( MB_LOG_ERROR, "SER-INIT", "Can't set settings for port %s: %s\n",
szDevice, strerror( errno ) );
}
else
{
vMBPortSerialEnable( FALSE, FALSE );
bStatus = TRUE;
}
}
}
return bStatus;
}
BOOL
xMBPortSerialSetTimeout( ULONG ulNewTimeoutMs )
{
if( ulNewTimeoutMs > 0 )
{
ulTimeoutMs = ulNewTimeoutMs;
}
else
{
ulTimeoutMs = 1;
}
return TRUE;
}
void
vMBPortClose( void )
{
if( iSerialFd != -1 )
{
( void )tcsetattr( iSerialFd, TCSANOW, &xOldTIO );
( void )close( iSerialFd );
iSerialFd = -1;
}
}
BOOL
prvbMBPortSerialRead( UCHAR * pucBuffer, USHORT usNBytes, USHORT * usNBytesRead )
{
BOOL bResult = TRUE;
ssize_t res;
fd_set rfds;
struct timeval tv;
// tv.tv_sec = 1;
// tv.tv_usec = 60000;
tv.tv_sec = 0;
tv.tv_usec = 10000; //lch fix
FD_ZERO( &rfds );
FD_SET( iSerialFd, &rfds );
/* Wait until character received or timeout. Recover in case of an
* interrupted read system call. */
do
{
if( select( iSerialFd + 1, &rfds, NULL, NULL, &tv ) == -1 )
{
if( errno != EINTR )
{
bResult = FALSE;
}
}
else if( FD_ISSET( iSerialFd, &rfds ) )
{
if( ( res = read( iSerialFd, pucBuffer, usNBytes ) ) == -1 )
{
bResult = FALSE;
}
else
{
*usNBytesRead = ( USHORT ) res;
break;
}
}
else
{
*usNBytesRead = 0;
break;
}
}
while( bResult == TRUE );
return bResult;
}
BOOL
prvbMBPortSerialWrite( UCHAR * pucBuffer, USHORT usNBytes )
{
ssize_t res;
size_t left = ( size_t ) usNBytes;
size_t done = 0;
while( left > 0 )
{
if( ( res = write( iSerialFd, pucBuffer + done, left ) ) == -1 )
{
if( errno != EINTR )
{
break;
}
/* call write again because of interrupted system call. */
continue;
}
done += res;
left -= res;
}
return left == 0 ? TRUE : FALSE;
}
BOOL
xMBPortSerialPoll( )
{
BOOL bStatus = TRUE;
USHORT usBytesRead;
int i;
while( bRxEnabled )
{
if( prvbMBPortSerialRead( &ucBuffer[0], BUF_SIZE, &usBytesRead ) )
{
if( usBytesRead == 0 )
{
/* timeout with no bytes. */
break;
}
else if( usBytesRead > 0 )
{
for( i = 0; i < usBytesRead; i++ )
{
/* Call the modbus stack and let him fill the buffers. */
( void )pxMBFrameCBByteReceived( );
}
uiRxBufferPos = 0;
}
}
else
{
vMBPortLog( MB_LOG_ERROR, "SER-POLL", "read failed on serial device: %s\n",
strerror( errno ) );
bStatus = FALSE;
}
}
if( bTxEnabled )
{
while( bTxEnabled )
{
( void )pxMBFrameCBTransmitterEmpty( );
/* Call the modbus stack to let him fill the buffer. */
}
if( !prvbMBPortSerialWrite( &ucBuffer[0], uiTxBufferPos ) )
{
vMBPortLog( MB_LOG_ERROR, "SER-POLL", "write failed on serial device: %s\n",
strerror( errno ) );
bStatus = FALSE;
}
}
return bStatus;
}
BOOL
xMBPortSerialPutByte( CHAR ucByte )
{
assert( uiTxBufferPos < BUF_SIZE );
ucBuffer[uiTxBufferPos] = ucByte;
uiTxBufferPos++;
return TRUE;
}
BOOL
xMBPortSerialGetByte( CHAR * pucByte )
{
assert( uiRxBufferPos < BUF_SIZE );
*pucByte = ucBuffer[uiRxBufferPos];
uiRxBufferPos++;
return TRUE;
}
+385 -385
View File
@@ -1,385 +1,385 @@
/*
* FreeModbus Libary: Win32 Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: porttcp.c,v 1.1 2007/09/12 10:15:56 wolti Exp $
*/
/*
* Design Notes:
*
* The xMBPortTCPInit function allocates a socket and binds the socket to
* all available interfaces ( bind with INADDR_ANY ). In addition it
* creates an array of event objects which is used to check the state of
* the clients. On event object is used to handle new connections or
* closed ones. The other objects are used on a per client basis for
* processing.
*/
/**********************************************************
* Linux TCP support.
* Based on Walter's project.
* Modified by Steven Guo <gotop167@163.com>
***********************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
//#include <QTcpServer>
/* ----------------------- MBAP Header --------------------------------------*/
#define MB_TCP_UID 6
#define MB_TCP_LEN 4
#define MB_TCP_FUNC 7
/* ----------------------- Defines -----------------------------------------*/
#define MB_TCP_DEFAULT_PORT 5022//5022 /* TCP listening port. */
#define MB_TCP_POOL_TIMEOUT 50 /* pool timeout for event waiting. */
#define MB_TCP_READ_TIMEOUT 1000 /* Maximum timeout to wait for packets. */
#define MB_TCP_READ_CYCLE 100 /* Time between checking for new data. */
#define MB_TCP_DEBUG 1 /* Set to 1 for additional debug output. */
#define MB_TCP_BUF_SIZE ( 256 + 7 ) /* Must hold a complete Modbus TCP frame. */
#define EV_CONNECTION 0
#define EV_CLIENT 1
#define EV_NEVENTS EV_CLIENT + 1
/* ----------------------- Static variables ---------------------------------*/
SOCKET xListenSocket;
SOCKET xClientSocket = INVALID_SOCKET;
static fd_set allset;
static UCHAR aucTCPBuf[MB_TCP_BUF_SIZE];
static USHORT usTCPBufPos;
static USHORT usTCPFrameBytesLeft;
/* ----------------------- External functions -------------------------------*/
CHAR *WsaError2String( int dwError );
/* ----------------------- Static functions ---------------------------------*/
BOOL prvMBTCPPortAddressToString( SOCKET xSocket, CHAR * szAddr, USHORT usBufSize );
CHAR *prvMBTCPPortFrameToString( UCHAR * pucFrame, USHORT usFrameLen );
static BOOL prvbMBPortAcceptClient( void );
static void prvvMBPortReleaseClient( void );
//static QTcpServer qListenSocket;
/* ----------------------- Begin implementation -----------------------------*/
BOOL
xMBTCPPortInit( USHORT usTCPPort )
{
USHORT usPort;
struct sockaddr_in serveraddr;
int tmp = 1;
if( usTCPPort == 0 )
{
usPort = MB_TCP_DEFAULT_PORT;
}
else
{
usPort = ( USHORT ) usTCPPort;
}
memset( &serveraddr, 0, sizeof( serveraddr ) );
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl( INADDR_ANY );
serveraddr.sin_port = htons( usPort );
if( ( xListenSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) == -1 )
{
fprintf( stderr, "Create socket failed.\r\n" );
return FALSE;
}
if(setsockopt(xListenSocket, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(int))<0)
{
fprintf( stderr, "setsockopt socket failed.\r\n" );
return FALSE;
}
if( bind( xListenSocket, ( struct sockaddr * )&serveraddr, sizeof( serveraddr ) ) == -1 )
{
fprintf( stderr, "Bind socket failed.\r\n" );
return FALSE;
}
else if( listen( xListenSocket, 1 ) == -1 )
{
fprintf( stderr, "Listen socket failed.\r\n" );
return FALSE;
}
FD_ZERO( &allset );
FD_SET( xListenSocket, &allset );
return TRUE;
}
void
vMBTCPPortClose( )
{
// Close all client sockets.
if( xClientSocket != SOCKET_ERROR )
{
prvvMBPortReleaseClient( );
}
// Close the listener socket.
if( xListenSocket != SOCKET_ERROR )
{
close( xListenSocket );
}
}
void
vMBTCPPortDisable( void )
{
/* Close all client sockets. */
if( xClientSocket != SOCKET_ERROR )
{
prvvMBPortReleaseClient( );
}
}
/*! \ingroup port_win32tcp
*
* \brief Pool the listening socket and currently connected Modbus TCP clients
* for new events.
* \internal
*
* This function checks if new clients want to connect or if already connected
* clients are sending requests. If a new client is connected and there are
* still client slots left (The current implementation supports only one)
* then the connection is accepted and an event object for the new client
* socket is activated (See prvbMBPortAcceptClient() ).
* Events for already existing clients in \c FD_READ and \c FD_CLOSE. In case of
* an \c FD_CLOSE the client connection is released (See prvvMBPortReleaseClient() ).
* In case of an \c FD_READ command the existing data is read from the client
* and if a complete frame has been received the Modbus Stack is notified.
*
* \return FALSE in case of an internal I/O error. For example if the internal
* event objects are in an invalid state. Note that this does not include any
* client errors. In all other cases returns TRUE.
*/
int errorCount = 0;
BOOL
xMBPortTCPPool( void )
{
int n;
fd_set fread;
struct timeval tval;
tval.tv_sec = 1;
tval.tv_usec = 60000;
int ret;
USHORT usLength;
if( xClientSocket == INVALID_SOCKET )
{
/* Accept to client */
if( ( n = select( xListenSocket + 1, &allset, NULL, NULL, NULL ) ) < 0 )
{
if( errno == EINTR )
{
;
}
else
{
;
}
}
if( FD_ISSET( xListenSocket, &allset ) )
{
( void )prvbMBPortAcceptClient( );
}
}
while( TRUE )
{
FD_ZERO( &fread );
FD_SET( xClientSocket, &fread );
if( ( ( ret = select( xClientSocket + 1, &fread, NULL, NULL, &tval ) ) == SOCKET_ERROR )
|| !ret )
{
sleep(1);
errorCount++;
if(errorCount > 10)
{
errorCount = 0;
close( xClientSocket );
xClientSocket = INVALID_SOCKET;
return TRUE;
}
continue;
}
if( ret > 0 )
{
if( FD_ISSET( xClientSocket, &fread ) )
{
if( ( ( ret =
recv( xClientSocket, &aucTCPBuf[usTCPBufPos], usTCPFrameBytesLeft,
0 ) ) == SOCKET_ERROR ) || ( !ret ) )
{
close( xClientSocket );
xClientSocket = INVALID_SOCKET;
return TRUE;
}
usTCPBufPos += ret;
usTCPFrameBytesLeft -= ret;
if( usTCPBufPos >= MB_TCP_FUNC )
{
/* Length is a byte count of Modbus PDU (function code + data) and the
* unit identifier. */
usLength = aucTCPBuf[MB_TCP_LEN] << 8U;
usLength |= aucTCPBuf[MB_TCP_LEN + 1];
/* Is the frame already complete. */
if( usTCPBufPos < ( MB_TCP_UID + usLength ) )
{
usTCPFrameBytesLeft = usLength + MB_TCP_UID - usTCPBufPos;
}
/* The frame is complete. */
else if( usTCPBufPos == ( MB_TCP_UID + usLength ) )
{
( void )xMBPortEventPost( EV_FRAME_RECEIVED );
return TRUE;
}
/* This can not happend because we always calculate the number of bytes
* to receive. */
else
{
assert( usTCPBufPos <= ( MB_TCP_UID + usLength ) );
}
}
}
}
}
return TRUE;
}
/*!
* \ingroup port_win32tcp
* \brief Receives parts of a Modbus TCP frame and if complete notifies
* the protocol stack.
* \internal
*
* This function reads a complete Modbus TCP frame from the protocol stack.
* It starts by reading the header with an initial request size for
* usTCPFrameBytesLeft = MB_TCP_FUNC. If the header is complete the
* number of bytes left can be calculated from it (See Length in MBAP header).
* Further read calls are issued until the frame is complete.
*
* \return \c TRUE if part of a Modbus TCP frame could be processed. In case
* of a communication error the function returns \c FALSE.
*/
BOOL
xMBTCPPortGetRequest( UCHAR ** ppucMBTCPFrame, USHORT * usTCPLength )
{
*ppucMBTCPFrame = &aucTCPBuf[0];
*usTCPLength = usTCPBufPos;
/* Reset the buffer. */
usTCPBufPos = 0;
usTCPFrameBytesLeft = MB_TCP_FUNC;
return TRUE;
}
BOOL
xMBTCPPortSendResponse( const UCHAR * pucMBTCPFrame, USHORT usTCPLength )
{
BOOL bFrameSent = FALSE;
BOOL bAbort = FALSE;
int res;
int iBytesSent = 0;
int iTimeOut = MB_TCP_READ_TIMEOUT;
do
{
res = send( xClientSocket, &pucMBTCPFrame[iBytesSent], usTCPLength - iBytesSent, 0 );
switch ( res )
{
case -1:
if( iTimeOut > 0 )
{
iTimeOut -= MB_TCP_READ_CYCLE;
usleep( MB_TCP_READ_CYCLE );
}
else
{
bAbort = TRUE;
}
break;
case 0:
prvvMBPortReleaseClient( );
bAbort = TRUE;
break;
default:
iBytesSent += res;
break;
}
}
while( ( iBytesSent != usTCPLength ) && !bAbort );
bFrameSent = iBytesSent == usTCPLength ? TRUE : FALSE;
return bFrameSent;
}
void
prvvMBPortReleaseClient( )
{
( void )recv( xClientSocket, &aucTCPBuf[0], MB_TCP_BUF_SIZE, 0 );
( void )close( xClientSocket );
xClientSocket = INVALID_SOCKET;
}
BOOL
prvbMBPortAcceptClient( )
{
SOCKET xNewSocket;
BOOL bOkay;
/* Check if we can handle a new connection. */
if( xClientSocket != INVALID_SOCKET )
{
fprintf( stderr, "can't accept new client. all connections in use.\n" );
bOkay = FALSE;
}
else if( ( xNewSocket = accept( xListenSocket, NULL, NULL ) ) == INVALID_SOCKET )
{
bOkay = FALSE;
}
else
{
xClientSocket = xNewSocket;
usTCPBufPos = 0;
usTCPFrameBytesLeft = MB_TCP_FUNC;
bOkay = TRUE;
}
return bOkay;
}
/*
* FreeModbus Libary: Win32 Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: porttcp.c,v 1.1 2007/09/12 10:15:56 wolti Exp $
*/
/*
* Design Notes:
*
* The xMBPortTCPInit function allocates a socket and binds the socket to
* all available interfaces ( bind with INADDR_ANY ). In addition it
* creates an array of event objects which is used to check the state of
* the clients. On event object is used to handle new connections or
* closed ones. The other objects are used on a per client basis for
* processing.
*/
/**********************************************************
* Linux TCP support.
* Based on Walter's project.
* Modified by Steven Guo <gotop167@163.com>
***********************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
//#include <QTcpServer>
/* ----------------------- MBAP Header --------------------------------------*/
#define MB_TCP_UID 6
#define MB_TCP_LEN 4
#define MB_TCP_FUNC 7
/* ----------------------- Defines -----------------------------------------*/
#define MB_TCP_DEFAULT_PORT 5022//5022 /* TCP listening port. */
#define MB_TCP_POOL_TIMEOUT 50 /* pool timeout for event waiting. */
#define MB_TCP_READ_TIMEOUT 1000 /* Maximum timeout to wait for packets. */
#define MB_TCP_READ_CYCLE 100 /* Time between checking for new data. */
#define MB_TCP_DEBUG 1 /* Set to 1 for additional debug output. */
#define MB_TCP_BUF_SIZE ( 256 + 7 ) /* Must hold a complete Modbus TCP frame. */
#define EV_CONNECTION 0
#define EV_CLIENT 1
#define EV_NEVENTS EV_CLIENT + 1
/* ----------------------- Static variables ---------------------------------*/
SOCKET xListenSocket;
SOCKET xClientSocket = INVALID_SOCKET;
static fd_set allset;
static UCHAR aucTCPBuf[MB_TCP_BUF_SIZE];
static USHORT usTCPBufPos;
static USHORT usTCPFrameBytesLeft;
/* ----------------------- External functions -------------------------------*/
CHAR *WsaError2String( int dwError );
/* ----------------------- Static functions ---------------------------------*/
BOOL prvMBTCPPortAddressToString( SOCKET xSocket, CHAR * szAddr, USHORT usBufSize );
CHAR *prvMBTCPPortFrameToString( UCHAR * pucFrame, USHORT usFrameLen );
static BOOL prvbMBPortAcceptClient( void );
static void prvvMBPortReleaseClient( void );
//static QTcpServer qListenSocket;
/* ----------------------- Begin implementation -----------------------------*/
BOOL
xMBTCPPortInit( USHORT usTCPPort )
{
USHORT usPort;
struct sockaddr_in serveraddr;
int tmp = 1;
if( usTCPPort == 0 )
{
usPort = MB_TCP_DEFAULT_PORT;
}
else
{
usPort = ( USHORT ) usTCPPort;
}
memset( &serveraddr, 0, sizeof( serveraddr ) );
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl( INADDR_ANY );
serveraddr.sin_port = htons( usPort );
if( ( xListenSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) == -1 )
{
fprintf( stderr, "Create socket failed.\r\n" );
return FALSE;
}
if(setsockopt(xListenSocket, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(int))<0)
{
fprintf( stderr, "setsockopt socket failed.\r\n" );
return FALSE;
}
if( bind( xListenSocket, ( struct sockaddr * )&serveraddr, sizeof( serveraddr ) ) == -1 )
{
fprintf( stderr, "Bind socket failed.\r\n" );
return FALSE;
}
else if( listen( xListenSocket, 1 ) == -1 )
{
fprintf( stderr, "Listen socket failed.\r\n" );
return FALSE;
}
FD_ZERO( &allset );
FD_SET( xListenSocket, &allset );
return TRUE;
}
void
vMBTCPPortClose( )
{
// Close all client sockets.
if( xClientSocket != SOCKET_ERROR )
{
prvvMBPortReleaseClient( );
}
// Close the listener socket.
if( xListenSocket != SOCKET_ERROR )
{
close( xListenSocket );
}
}
void
vMBTCPPortDisable( void )
{
/* Close all client sockets. */
if( xClientSocket != SOCKET_ERROR )
{
prvvMBPortReleaseClient( );
}
}
/*! \ingroup port_win32tcp
*
* \brief Pool the listening socket and currently connected Modbus TCP clients
* for new events.
* \internal
*
* This function checks if new clients want to connect or if already connected
* clients are sending requests. If a new client is connected and there are
* still client slots left (The current implementation supports only one)
* then the connection is accepted and an event object for the new client
* socket is activated (See prvbMBPortAcceptClient() ).
* Events for already existing clients in \c FD_READ and \c FD_CLOSE. In case of
* an \c FD_CLOSE the client connection is released (See prvvMBPortReleaseClient() ).
* In case of an \c FD_READ command the existing data is read from the client
* and if a complete frame has been received the Modbus Stack is notified.
*
* \return FALSE in case of an internal I/O error. For example if the internal
* event objects are in an invalid state. Note that this does not include any
* client errors. In all other cases returns TRUE.
*/
int errorCount = 0;
BOOL
xMBPortTCPPool( void )
{
int n;
fd_set fread;
struct timeval tval;
tval.tv_sec = 1;
tval.tv_usec = 60000;
int ret;
USHORT usLength;
if( xClientSocket == INVALID_SOCKET )
{
/* Accept to client */
if( ( n = select( xListenSocket + 1, &allset, NULL, NULL, NULL ) ) < 0 )
{
if( errno == EINTR )
{
;
}
else
{
;
}
}
if( FD_ISSET( xListenSocket, &allset ) )
{
( void )prvbMBPortAcceptClient( );
}
}
while( TRUE )
{
FD_ZERO( &fread );
FD_SET( xClientSocket, &fread );
if( ( ( ret = select( xClientSocket + 1, &fread, NULL, NULL, &tval ) ) == SOCKET_ERROR )
|| !ret )
{
sleep(1);
errorCount++;
if(errorCount > 10)
{
errorCount = 0;
close( xClientSocket );
xClientSocket = INVALID_SOCKET;
return TRUE;
}
continue;
}
if( ret > 0 )
{
if( FD_ISSET( xClientSocket, &fread ) )
{
if( ( ( ret =
recv( xClientSocket, &aucTCPBuf[usTCPBufPos], usTCPFrameBytesLeft,
0 ) ) == SOCKET_ERROR ) || ( !ret ) )
{
close( xClientSocket );
xClientSocket = INVALID_SOCKET;
return TRUE;
}
usTCPBufPos += ret;
usTCPFrameBytesLeft -= ret;
if( usTCPBufPos >= MB_TCP_FUNC )
{
/* Length is a byte count of Modbus PDU (function code + data) and the
* unit identifier. */
usLength = aucTCPBuf[MB_TCP_LEN] << 8U;
usLength |= aucTCPBuf[MB_TCP_LEN + 1];
/* Is the frame already complete. */
if( usTCPBufPos < ( MB_TCP_UID + usLength ) )
{
usTCPFrameBytesLeft = usLength + MB_TCP_UID - usTCPBufPos;
}
/* The frame is complete. */
else if( usTCPBufPos == ( MB_TCP_UID + usLength ) )
{
( void )xMBPortEventPost( EV_FRAME_RECEIVED );
return TRUE;
}
/* This can not happend because we always calculate the number of bytes
* to receive. */
else
{
assert( usTCPBufPos <= ( MB_TCP_UID + usLength ) );
}
}
}
}
}
return TRUE;
}
/*!
* \ingroup port_win32tcp
* \brief Receives parts of a Modbus TCP frame and if complete notifies
* the protocol stack.
* \internal
*
* This function reads a complete Modbus TCP frame from the protocol stack.
* It starts by reading the header with an initial request size for
* usTCPFrameBytesLeft = MB_TCP_FUNC. If the header is complete the
* number of bytes left can be calculated from it (See Length in MBAP header).
* Further read calls are issued until the frame is complete.
*
* \return \c TRUE if part of a Modbus TCP frame could be processed. In case
* of a communication error the function returns \c FALSE.
*/
BOOL
xMBTCPPortGetRequest( UCHAR ** ppucMBTCPFrame, USHORT * usTCPLength )
{
*ppucMBTCPFrame = &aucTCPBuf[0];
*usTCPLength = usTCPBufPos;
/* Reset the buffer. */
usTCPBufPos = 0;
usTCPFrameBytesLeft = MB_TCP_FUNC;
return TRUE;
}
BOOL
xMBTCPPortSendResponse( const UCHAR * pucMBTCPFrame, USHORT usTCPLength )
{
BOOL bFrameSent = FALSE;
BOOL bAbort = FALSE;
int res;
int iBytesSent = 0;
int iTimeOut = MB_TCP_READ_TIMEOUT;
do
{
res = send( xClientSocket, &pucMBTCPFrame[iBytesSent], usTCPLength - iBytesSent, 0 );
switch ( res )
{
case -1:
if( iTimeOut > 0 )
{
iTimeOut -= MB_TCP_READ_CYCLE;
usleep( MB_TCP_READ_CYCLE );
}
else
{
bAbort = TRUE;
}
break;
case 0:
prvvMBPortReleaseClient( );
bAbort = TRUE;
break;
default:
iBytesSent += res;
break;
}
}
while( ( iBytesSent != usTCPLength ) && !bAbort );
bFrameSent = iBytesSent == usTCPLength ? TRUE : FALSE;
return bFrameSent;
}
void
prvvMBPortReleaseClient( )
{
( void )recv( xClientSocket, &aucTCPBuf[0], MB_TCP_BUF_SIZE, 0 );
( void )close( xClientSocket );
xClientSocket = INVALID_SOCKET;
}
BOOL
prvbMBPortAcceptClient( )
{
SOCKET xNewSocket;
BOOL bOkay;
/* Check if we can handle a new connection. */
if( xClientSocket != INVALID_SOCKET )
{
fprintf( stderr, "can't accept new client. all connections in use.\n" );
bOkay = FALSE;
}
else if( ( xNewSocket = accept( xListenSocket, NULL, NULL ) ) == INVALID_SOCKET )
{
bOkay = FALSE;
}
else
{
xClientSocket = xNewSocket;
usTCPBufPos = 0;
usTCPFrameBytesLeft = MB_TCP_FUNC;
bOkay = TRUE;
}
return bOkay;
}
+97 -97
View File
@@ -1,97 +1,97 @@
/*
* FreeModbus Libary: Linux Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: porttimer.c,v 1.1 2006/08/01 20:58:50 wolti Exp $
*/
/* ----------------------- Standard includes --------------------------------*/
#include <stdlib.h>
#include <sys/time.h>
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
/* ----------------------- Defines ------------------------------------------*/
/* ----------------------- Static variables ---------------------------------*/
ULONG ulTimeOut;
BOOL bTimeoutEnable;
static struct timeval xTimeLast;
/* ----------------------- Start implementation -----------------------------*/
BOOL
xMBPortTimersInit( USHORT usTim1Timerout50us )
{
ulTimeOut = usTim1Timerout50us / 20U;
if( ulTimeOut == 0 )
ulTimeOut = 1;
return xMBPortSerialSetTimeout( ulTimeOut );
}
void
xMBPortTimersClose( )
{
/* Does not use any hardware resources. */
}
void
vMBPortTimerPoll( )
{
ULONG ulDeltaMS;
struct timeval xTimeCur;
/* Timers are called from the serial layer because we have no high
* res timer in Win32. */
if( bTimeoutEnable )
{
if( gettimeofday( &xTimeCur, NULL ) != 0 )
{
/* gettimeofday failed - retry next time. */
}
else
{
ulDeltaMS = ( xTimeCur.tv_sec - xTimeLast.tv_sec ) * 1000L +
( xTimeCur.tv_usec - xTimeLast.tv_usec ) * 1000L;
if( ulDeltaMS > ulTimeOut )
{
bTimeoutEnable = FALSE;
( void )pxMBPortCBTimerExpired( );
}
}
}
}
void
vMBPortTimersEnable( )
{
int res = gettimeofday( &xTimeLast, NULL );
assert( res == 0 );
bTimeoutEnable = TRUE;
}
void
vMBPortTimersDisable( )
{
bTimeoutEnable = FALSE;
}
/*
* FreeModbus Libary: Linux Port
* Copyright (C) 2006 Christian Walter <wolti@sil.at>
*
* This 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* File: $Id: porttimer.c,v 1.1 2006/08/01 20:58:50 wolti Exp $
*/
/* ----------------------- Standard includes --------------------------------*/
#include <stdlib.h>
#include <sys/time.h>
#include "port.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"
/* ----------------------- Defines ------------------------------------------*/
/* ----------------------- Static variables ---------------------------------*/
ULONG ulTimeOut;
BOOL bTimeoutEnable;
static struct timeval xTimeLast;
/* ----------------------- Start implementation -----------------------------*/
BOOL
xMBPortTimersInit( USHORT usTim1Timerout50us )
{
ulTimeOut = usTim1Timerout50us / 20U;
if( ulTimeOut == 0 )
ulTimeOut = 1;
return xMBPortSerialSetTimeout( ulTimeOut );
}
void
xMBPortTimersClose( )
{
/* Does not use any hardware resources. */
}
void
vMBPortTimerPoll( )
{
ULONG ulDeltaMS;
struct timeval xTimeCur;
/* Timers are called from the serial layer because we have no high
* res timer in Win32. */
if( bTimeoutEnable )
{
if( gettimeofday( &xTimeCur, NULL ) != 0 )
{
/* gettimeofday failed - retry next time. */
}
else
{
ulDeltaMS = ( xTimeCur.tv_sec - xTimeLast.tv_sec ) * 1000L +
( xTimeCur.tv_usec - xTimeLast.tv_usec ) * 1000L;
if( ulDeltaMS > ulTimeOut )
{
bTimeoutEnable = FALSE;
( void )pxMBPortCBTimerExpired( );
}
}
}
}
void
vMBPortTimersEnable( )
{
int res = gettimeofday( &xTimeLast, NULL );
assert( res == 0 );
bTimeoutEnable = TRUE;
}
void
vMBPortTimersDisable( )
{
bTimeoutEnable = FALSE;
}