2.13 Communications with a Windows PC (Visual C++ Application)
Using Automatic Reception with the MP3000 as a Slave
2-349
• Programming Example for Extended MEMOBUS Protocol Message Communications
The programming example that is given below demonstrates how to manage sockets and perform mes-
sage communications using the Extended MEMOBUS protocol.
This program example is written in C language so it must declare extern “C” to make calls from C++.
#include <stdio.h>
#include <winsock.h>
#include <winioctl.h>
#define TCP_PRT 0
#define UDP_PRT 1
#define DATA_SIZE 4096
int sd; /∗ Socket Discripter ∗/
struct sockaddr_in my;
struct sockaddr_in dst;
struct sockaddr_in from;
short DATAi; // Number of data items to send
short MDATAi; // MEMOBUS data length
unsigned char iSerial; // Serial number
// Protocol declaration
int memobus_master_main( unsigned short trans_prt, unsigned long myip,
unsigned short myport, unsigned long dstip, unsigned short dstport );
int memobus_msg( unsigned short trans_prt, char∗ sbuf, char∗ rbuf );
int tcp_msg( char∗ sbuf, char∗ rbuf );
int udp_msg( char∗ sbuf, char∗ rbuf );
void mk_cmd_data( unsigned char SFC, unsigned char CPUNum,
unsigned short Adr, unsigned short DataNum, char∗ sbuf );
int chk_rsp_data( int rlen, char∗ sbuf, char∗ rbuf );
/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗/
/∗ Open a TCP/UDP port ∗/
/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗/
int memobus_master_main( unsigned short trans_prt,
unsigned long myip, unsigned short myport,
unsigned long dstip, unsigned short dstport )
{
WSADATA wsadata;
int rc;
// Declaration to use Winsock.dll (must be declared before calling routines)
rc = WSAStartup( 0x0101, &wsadata );
if ( rc != 0 )
{
exit(0);
}