plc.myforum.ro Forum Index plc.myforum.ro
PLCs users www.plc.myforum.ro!
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

How to access Modbus TCP Conection Status/IP via C in WinCC

 
Post new topic   Reply to topic    plc.myforum.ro Forum Index -> SIMATIC Automation Systems -Reg.U
View previous topic :: View next topic  
Author Message
cgjJounior
Junior
Junior


Joined: 27 May 2015
Posts: 14

PostPosted: 13/08/2016 09:51    Post subject: How to access Modbus TCP Conection Status/IP via C in WinCC Reply with quote

Hi dear experts. According to the attached picture I want to access the status and connection driver IP address of my Modbus TCPIP channel drivers via C-Script in WinCC. Can anyone suggest me a function or a script code.
[img][url]http://jahadgar.persiangig.com/modbus%20tcpip%20connection.jpg[/url][/img]
Back to top
View user's profile Send private message
baroso
Junior 2
Junior 2


Joined: 29 Jul 2016
Posts: 22

PostPosted: 01/12/2016 12:30    Post subject: Re: How to access Modbus TCP Conection Status/IP via C in Wi Reply with quote

cgjJounior wrote:
Hi dear experts. According to the attached picture I want to access the status and connection driver IP address of my Modbus TCPIP channel drivers via C-Script in WinCC. Can anyone suggest me a function or a script code.
[img][url]http://jahadgar.persiangig.com/modbus%20tcpip%20connection.jpg[/url][/img]

TCP/IP Use a wsock32.dll, realizate an action, poll these action and listen on a socket.
Another metod is to use OPC Server to access what you need

Code:
#include "apdefap.h"

int gscAction( void )
{

  // Include header files
  #include "WSOCK32.h"

   #define METNET_HOSTNAME                     "METNET"  // defined in %SYSTEM%\System32\drivers\etc\lmhosts or hosts
  #define METNET_SERVICENAME               "metnet"  // defined in %SYSTEM%\System32\drivers\etc\services

  // Declare local variables
  WSADATA         wsaData;
  long         lResult = 0;
  BOOL         bResult = FALSE;
  SOCKET         sMetNet = INVALID_SOCKET;
  struct hostent   *pheMetNet = NULL;
  struct servent   *pseMetNet = NULL;
  struct sockaddr_in   saAddress;
  unsigned long      ulCommand = 1;
  char         szTelegramData[1024] = "";

  // Get actual communication socket with MetNet-Server
  sMetNet = (SOCKET)GetTagSDWord(HMI_SA_METNETSOCKET);   // Tag Signed 16-Bit Value

  // Examine for active connection with MetNet-Server
  if( (sMetNet == INVALID_SOCKET) || (sMetNet == 0) )
  {
 
    // Get actual MetNet-Communication parameters
    pheMetNet = gethostbyname(METNET_HOSTNAME);
    if( !pheMetNet )
    {
      GetSocketError(0, "Cannot resolve hostname [%s]", METNET_HOSTNAME);
      return(-1);
    }
    pseMetNet = getservbyname(METNET_SERVICENAME, "tcp");
    if( !pseMetNet )
    {
      GetSocketError(0, "Cannot resolve service [%s]", METNET_SERVICENAME);
      return(-1);
    }

    // Prepare communication parameter with MetNet-Server
    saAddress.sin_addr = *(struct in_addr*)pheMetNet->h_addr;
    saAddress.sin_family = AF_INET;
    saAddress.sin_port = pseMetNet->s_port;

    // Făcute communication socket
    sMetNet = socket(AF_INET, SOCK_STREAM, 0);
    if( sMetNet == SOCKET_ERROR )
    {
      GetSocketError(0, "Cannot create socket");
      return(-1);
    }

    // Open communication with MetNet-Server
    lResult = connect(sMetNet, (const struct sockaddr *)&saAddress, sizeof(saAddress));
    if( lResult == SOCKET_ERROR )
    {
      GetSocketError(sMetNet, "Cannot connect to server %s", METNET_HOSTNAME);
      return(-1);
    }
    else
    {
   
      // Set communication socket for nonblocking
      lResult = ioctlsocket(sMetNet, FIONBIO, &ulCommand);
      if( lResult == SOCKET_ERROR )
      {
        GetSocketError(sMetNet, "Cannot set communication socket for nonblocking");
        return(-1);
      }

      // Remember communication socket with MetNet-Server
      SetTagSDWord(HMI_SA_METNETSOCKET, sMetNet);

      printf("-- MetNet Connect -----------------------------------------------------------------------\r\n");
      printf(
              "Server\t: %s (IP: %d.%d.%d.%d)\r\n",
              pheMetNet->h_name,
              (unsigned char)pheMetNet->h_addr_list[0][0],
              (unsigned char)pheMetNet->h_addr_list[0][1],
              (unsigned char)pheMetNet->h_addr_list[0][2],
              (unsigned char)pheMetNet->h_addr_list[0][3]
            );
      printf("Port\t: %s (Port: %d)\r\n", pseMetNet->s_name, htons(pseMetNet->s_port));
      printf("------------------------------------------------------------------------------------------------------\r\n");
     
    }

  }

  // Receive data from communication MetNet-Server
  lResult = recv(sMetNet, &szTelegramData[0], (sizeof(szTelegramData) - 1), 0);
  if( (lResult > 0) && (WSAGetLastError() == 0) )
  {

    // Terminate receive telegram data
    szTelegramData[lResult] = '\0';

    // Your code ...
      
  }
  else
  {

    // Examine for socket failure (e.g. network error)
    if( (lResult == 0) && (WSAGetLastError() != WSAEWOULDBLOCK) )
    {

      // Close communication with MetNet-Server
      sMetNet = GetSocketError(sMetNet, "Cannot read data from server %s", METNET_HOSTNAME);

    }

  }

  // Finish action
  return(1);
 
}


Code:

// Conține header files
#include "WSOCK32.h"

unsigned int GetSocketError(unsigned int sSocket, char *lpszFormatMessage, ...)
{

  // Declare local variables
  va_list      vlErrorValues;
  int         iLastSocketError = 0;
  int         iNewSocketError = 0;
  static char   szLastErrorMessage[254 + 1] = "";
  char          szNewErrorMessage[254 + 1] = "";

  // Get last and new socket error
  iNewSocketError = WSAGetLastError();

  // Get new error message
  if( lpszFormatMessage != NULL )
  {
    va_start(vlErrorValues, lpszFormatMessage);
    vsprintf(&szNewErrorMessage[0], lpszFormatMessage, vlErrorValues);
    va_end(vlErrorValues);
  }

  // Close open communication socket
  if( sSocket > 0 )
  {
    shutdown(sSocket, 2);
    closesocket(sSocket);
    SetTagSDWord(HMI_SA_METNETSOCKET, INVALID_SOCKET);
  }

  // Write socket error message
  printf("== SOCKET ERROR =========================================\r\n");
  printf("  Socket error\t:  %d\r\n", iNewSocketError);
  if( strlen(&szNewErrorMessage[0]) > 0 )
    printf("  Error message\t:  %s\r\n", &szNewErrorMessage[0]);
  printf("=========================================================\r\n");

  // Finish function
  return(INVALID_SOCKET);

}



Code:

//--------------------------------------------------------------------------------
//
// Function   :   WSOCK32.H Winsocket definitions
//
// Reference   :   Definitions to be used with the WSOCK32.DLL
//
//--------------------------------------------------------------------------------

#ifndef __WSOCK32

#define __WSOCK32 1

// Basic system type definitions, taken from the BSD file sys/types.h
typedef unsigned char      u_char;
typedef unsigned short   u_short;
typedef unsigned int      u_int;
typedef unsigned long      u_long;
typedef int         INT_PTR, *PINT_PTR;
typedef unsigned int      UINT_PTR, *PUINT_PTR;
typedef long         LONG_PTR, *PLONG_PTR;
typedef unsigned long      ULONG_PTR, *PULONG_PTR;

// The new type to be used in all instances which refer to sockets
typedef INT_PTR   SOCKET;

//
#define WSADESCRIPTION_LEN      256
#define WSASYS_STATUS_LEN       128

typedef struct WSAData
{
  WORD                    wVersion;
  WORD                    wHighVersion;
  char                    szDescription[WSADESCRIPTION_LEN+1];
  char                    szSystemStatus[WSASYS_STATUS_LEN+1];
  unsigned short          iMaxSockets;
  unsigned short          iMaxUdpDg;
  char FAR *              lpVendorInfo;
} WSADATA;

typedef WSADATA *LPWSADATA;

// Internet address (old style... should be updated)
#ifndef s_addr

struct in_addr {
        union {
                struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
                struct { u_short s_w1,s_w2; } S_un_w;
                u_long S_addr;
        } S_un;
        #define s_addr  S_un.S_addr      // can be used for most tcp & ip code
        #define s_host  S_un.S_un_b.s_b2   // host on imp
        #define s_net   S_un.S_un_b.s_b1   // network
        #define s_imp   S_un.S_un_w.s_w2   // imp
        #define s_impno S_un.S_un_b.s_b4   // imp #
        #define s_lh    S_un.S_un_b.s_b3   // logical host
};

#endif

// Socket address, internet style
struct sockaddr_in
{
   short   sin_family;
   u_short sin_port;
   struct  in_addr sin_addr;
   char    sin_zero[8];
};

// Structures returned by network data base library, taken from the
// BSD file netdb.h.  All addresses are supplied in host order, and
// returned in network order (suitable for use in system calls).
struct  hostent
{
   char    FAR * h_name;              // official name of host
   char    FAR * FAR * h_aliases;      // alias list
   short   h_addrtype;            // host address type
   short   h_length;                  // length of address
   char    FAR * FAR * h_addr_list;   // list of addresses
   #define h_addr  h_addr_list[0]      // address, for backward compat
};

struct  servent
{
   char    FAR * s_name;            // official service name
   char    FAR * FAR * s_aliases;      // alias list
   short   s_port;                    // port #
   char    FAR * s_proto;             // protocol to use
};


// Commands for ioctlsocket(),  taken from the BSD file fcntl.h.
#define IOCPARM_MASK    0x7f              // parameters must be < 128 bytes
#define IOC_VOID        0x20000000         // no parameters
#define IOC_OUT         0x40000000         // copy out parameters
#define IOC_IN          0x80000000       // copy in parameters
#define IOC_INOUT       (IOC_IN|IOC_OUT)   // 0x20000000 distinguishes new & old ioctl's

#define _IO(x,y)        (IOC_VOID|((x)<<8)|(y))
#define _IOR(x,y,t)     (IOC_OUT|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y))
#define _IOW(x,y,t)     (IOC_IN|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y))

#define FIONREAD    _IOR('f', 127, u_long) // get # bytes to read
#define FIONBIO     _IOW('f', 126, u_long) // set/clear non-blocking i/o
#define FIOASYNC    _IOW('f', 125, u_long) // set/clear async i/o


// This is used instead of -1, since the SOCKET type is unsigned.
#define INVALID_SOCKET  (SOCKET)(~0)
#define SOCKET_ERROR            (-1)

// Types
#define SOCK_STREAM     1                  // stream socket

// Address families.
#define AF_UNSPEC       0            // unspecified
#define AF_UNIX         1            // local to host (pipes, portals)
#define AF_INET         2                  // internetwork: UDP, TCP, etc.
#define AF_IMPLINK      3                  // arpanet imp addresses
#define AF_PUP          4                  // pup protocols: e.g. BSP
#define AF_CHAOS        5                  // mit CHAOS protocols
#define AF_IPX          6                  // IPX and SPX */
#define AF_NS           6                  // XEROX NS protocols
#define AF_ISO          7                  // ISO protocols
#define AF_OSI          AF_ISO             // OSI is ISO
#define AF_ECMA         8                  // european computer manufacturers
#define AF_DATAKIT      9                  // datakit protocols
#define AF_CCITT        10                 // CCITT protocols, X.25 etc
#define AF_SNA          11                 // IBM SNA
#define AF_DECnet       12                 // DECnet
#define AF_DLI          13                 // Direct data link interface
#define AF_LAT          14                 // LAT
#define AF_HYLINK       15                 // NSC Hyperchannel
#define AF_APPLETALK    16                 // AppleTalk
#define AF_NETBIOS      17                 // NetBios-style addresses
#define AF_VOICEVIEW    18                 // VoiceView
#define AF_FIREFOX      19                 // FireFox
#define AF_UNKNOWN1     20                 // Somebody is using this!
#define AF_BAN          21                 // Banyan
#define AF_MAX          22            // Max address families

// Structure used by kernel to store most addresses.
struct sockaddr
{
   u_short sa_family;                 // address family
   char    sa_data[14];           // up to 14 bytes of direct address
};

// WinSock error codes are also defined in winerror.h
#ifndef WSABASEERR
#define WSABASEERR              10000
#define WSAEINTR                (WSABASEERR+4)
#define WSAEBADF                (WSABASEERR+9)
#define WSAEACCES               (WSABASEERR+13)
#define WSAEFAULT               (WSABASEERR+14)
#define WSAEINVAL               (WSABASEERR+22)
#define WSAEMFILE               (WSABASEERR+24)
#define WSAEWOULDBLOCK          (WSABASEERR+35)
#define WSAEINPROGRESS          (WSABASEERR+36)
#define WSAEALREADY             (WSABASEERR+37)
#define WSAENOTSOCK             (WSABASEERR+38)
#define WSAEDESTADDRREQ         (WSABASEERR+39)
#define WSAEMSGSIZE             (WSABASEERR+40)
#define WSAEPROTOTYPE           (WSABASEERR+41)
#define WSAENOPROTOOPT          (WSABASEERR+42)
#define WSAEPROTONOSUPPORT      (WSABASEERR+43)
#define WSAESOCKTNOSUPPORT      (WSABASEERR+44)
#define WSAEOPNOTSUPP           (WSABASEERR+45)
#define WSAEPFNOSUPPORT         (WSABASEERR+46)
#define WSAEAFNOSUPPORT         (WSABASEERR+47)
#define WSAEADDRINUSE           (WSABASEERR+48)
#define WSAEADDRNOTAVAIL        (WSABASEERR+49)
#define WSAENETDOWN             (WSABASEERR+50)
#define WSAENETUNREACH          (WSABASEERR+51)
#define WSAENETRESET            (WSABASEERR+52)
#define WSAECONNABORTED         (WSABASEERR+53)
#define WSAECONNRESET           (WSABASEERR+54)
#define WSAENOBUFS              (WSABASEERR+55)
#define WSAEISCONN              (WSABASEERR+56)
#define WSAENOTCONN             (WSABASEERR+57)
#define WSAESHUTDOWN            (WSABASEERR+58)
#define WSAETOOMANYREFS         (WSABASEERR+59)
#define WSAETIMEDOUT            (WSABASEERR+60)
#define WSAECONNREFUSED         (WSABASEERR+61)
#define WSAELOOP                (WSABASEERR+62)
#define WSAENAMETOOLONG         (WSABASEERR+63)
#define WSAEHOSTDOWN            (WSABASEERR+64)
#define WSAEHOSTUNREACH         (WSABASEERR+65)
#define WSAENOTEMPTY            (WSABASEERR+66)
#define WSAEPROCLIM             (WSABASEERR+67)
#define WSAEUSERS               (WSABASEERR+68)
#define WSAEDQUOT               (WSABASEERR+69)
#define WSAESTALE               (WSABASEERR+70)
#define WSAEREMOTE              (WSABASEERR+71)
#define WSASYSNOTREADY          (WSABASEERR+91)
#define WSAVERNOTSUPPORTED      (WSABASEERR+92)
#define WSANOTINITIALISED       (WSABASEERR+93)
#define WSAEDISCON              (WSABASEERR+101)
#define WSAHOST_NOT_FOUND       (WSABASEERR+1001)
#define WSATRY_AGAIN            (WSABASEERR+1002)
#define WSANO_RECOVERY          (WSABASEERR+1003)
#define WSANO_DATA              (WSABASEERR+1004)
#endif                      // ifdef WSABASEERR

// Winsocket function declaration from WSOCK32.DLL
#pragma code("wsock32.dll")
int WSAGetLastError(void);
int WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData);
int WSACleanup(void);
struct hostent *gethostbyname(const char FAR *name);
struct servent *getservbyname(const char FAR *name, const char FAR *proto);
SOCKET socket(int af, int type, int protocol);
int connect(SOCKET s, const struct sockaddr FAR *name, int namelen);
int ioctlsocket(SOCKET s, long cmd,u_long FAR *argp);
int shutdown(SOCKET s, int how);
int closesocket(SOCKET s);
int send(SOCKET s, const char FAR *buf, int len, int flags);
int recv(SOCKET s, char FAR * buf, int len, int flags);
u_long PASCAL FAR ntohl (IN u_long netlong);
u_short PASCAL FAR ntohs (IN u_short netshort);
u_long PASCAL FAR htonl ( IN u_long hostlong);
u_short PASCAL FAR htons (IN u_short hostshort);
unsigned long PASCAL FAR inet_addr (IN const char FAR * cp);
char FAR * PASCAL FAR inet_ntoa (IN struct in_addr in);
#pragma code()


#endif /* ifdef WSOCK32.h */
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    plc.myforum.ro Forum Index -> SIMATIC Automation Systems -Reg.U All times are GMT + 2 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group
Fa-ti si tu propriul forum GRATUIT, pe www.myforum.ro