1 /*=============================================================================|
2 |  PROJECT SNAP7                                                         1.3.0 |
3 |==============================================================================|
4 |  Copyright (C) 2013, 2014 Davide Nardella                                    |
5 |  All rights reserved.                                                        |
6 |==============================================================================|
7 |  SNAP7 is free software: you can redistribute it and/or modify               |
8 |  it under the terms of the Lesser GNU General Public License as published by |
9 |  the Free Software Foundation, either version 3 of the License, or           |
10 |  (at your option) any later version.                                         |
11 |                                                                              |
12 |  It means that you can distribute your commercial software linked with       |
13 |  SNAP7 without the requirement to distribute the source code of your         |
14 |  application and without the requirement that your application be itself     |
15 |  distributed under LGPL.                                                     |
16 |                                                                              |
17 |  SNAP7 is distributed in the hope that it will be useful,                    |
18 |  but WITHOUT ANY WARRANTY; without even the implied warranty of              |
19 |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               |
20 |  Lesser GNU General Public License for more details.                         |
21 |                                                                              |
22 |  You should have received a copy of the GNU General Public License and a     |
23 |  copy of Lesser GNU General Public License along with Snap7.                 |
24 |  If not, see  http://www.gnu.org/licenses/                                   |
25 |==============================================================================|
26 |                                                                              |
27 |  C/C++ Snap 7 classes/Imports definitions                                    |
28 |                                                                              |
29 |=============================================================================*/
30 #ifndef snap7_h
31 #define snap7_h
32 //---------------------------------------------------------------------------
33 // Platform detection
34 //---------------------------------------------------------------------------
35 #if defined (_WIN32)||defined(_WIN64)||defined(__WIN32__)||defined(__WINDOWS__)
36 # define OS_WINDOWS
37 #endif
38 
39 // Visual Studio needs this to use the correct time_t size
40 #if defined (_WIN32) && !defined(_WIN64)
41 # define _USE_32BIT_TIME_T
42 #endif
43 
44 #if defined(unix) || defined(__unix__) || defined(__unix)
45 # define PLATFORM_UNIX
46 #endif
47 
48 #if defined(__SVR4) || defined(__svr4__)
49 # define OS_SOLARIS
50 #endif
51 
52 #if BSD>=0
53 # define OS_BSD
54 #endif
55 
56 #if defined(__APPLE__)
57 # define OS_OSX
58 #endif
59 
60 #if defined(PLATFORM_UNIX) || defined(OS_OSX)
61 # include <unistd.h>
62 # if defined(_POSIX_VERSION)
63 #   define POSIX
64 # endif
65 #endif
66 
67 //---------------------------------------------------------------------------
68 // C++ Library
69 //---------------------------------------------------------------------------
70 #ifdef __cplusplus
71 #include <string>
72 #include <time.h>
73 
74 // Visual C++ not C99 compliant (VS2008--)
75 #ifdef _MSC_VER
76 # if _MSC_VER >= 1600
77 #  include <stdint.h>  // VS2010++ have it
78 # else
79    typedef signed __int8     int8_t;
80    typedef signed __int16    int16_t;
81    typedef signed __int32    int32_t;
82    typedef signed __int64    int64_t;
83    typedef unsigned __int8   uint8_t;
84    typedef unsigned __int16  uint16_t;
85    typedef unsigned __int32  uint32_t;
86    typedef unsigned __int64  uint64_t;
87    #ifdef _WIN64
88      typedef unsigned __int64  uintptr_t;
89    #else
90      typedef unsigned __int32  uintptr_t;
91    #endif
92 # endif
93 #else
94 # include <stdint.h>
95 #endif
96 
97 extern "C" {
98 #endif
99 //---------------------------------------------------------------------------
100 // C exact length types
101 //---------------------------------------------------------------------------
102 #ifndef __cplusplus
103 
104 #ifdef OS_BSD
105 #  include <stdint.h>
106 #  include <time.h>
107 #endif
108 
109 #ifdef OS_OSX
110 #  include <stdint.h>
111 #  include <time.h>
112 #endif
113 
114 #ifdef OS_SOLARIS
115 #  include <stdint.h>
116 #  include <time.h>
117 #endif
118 
119 #if defined(_UINTPTR_T_DEFINED)
120 #  include <stdint.h>
121 #  include <time.h>
122 #endif
123 
124 #if !defined(_UINTPTR_T_DEFINED) && !defined(OS_SOLARIS) && !defined(OS_BSD) && !defined(OS_OSX)
125   typedef unsigned char   uint8_t;  //  8 bit unsigned integer
126   typedef unsigned short  uint16_t; // 16 bit unsigned integer
127   typedef unsigned int    uint32_t; // 32 bit unsigned integer
128   typedef unsigned long   uintptr_t;// 64 bit unsigned integer
129 #endif
130 
131 #endif
132 
133 #ifdef OS_WINDOWS
134 # define S7API __stdcall
135 #else
136 # define S7API
137 #endif
138 
139 #pragma pack(1)
140 //******************************************************************************
141 //                                   COMMON
142 //******************************************************************************
143 // Exact length types regardless of platform/processor
144 typedef uint8_t    byte;
145 typedef uint16_t   word;
146 typedef int16_t    smallint;
147 typedef uint32_t   longword;
148 typedef int32_t    longint;
149 typedef byte       *pbyte;
150 typedef word       *pword;
151 typedef longword   *plongword;
152 typedef smallint   *psmallint;
153 typedef longint    *plongint;
154 typedef float      *pfloat;
155 typedef uintptr_t  S7Object; // multi platform/processor object reference
156                              // DON'T CONFUSE IT WITH AN OLE OBJECT, IT'S SIMPLY
157                              // AN INTEGER VALUE (32 OR 64 BIT) USED AS HANDLE.
158 
159 #ifndef __cplusplus
160 typedef struct
161 {
162   int   tm_sec;
163   int   tm_min;
164   int   tm_hour;
165   int   tm_mday;
166   int   tm_mon;
167   int   tm_year;
168   int   tm_wday;
169   int   tm_yday;
170   int   tm_isdst;
171 }tm;
172 
173 typedef int bool;
174 #define false 0;
175 #define true  1;
176 #endif
177 
178 const int errLibInvalidParam  = -1;
179 const int errLibInvalidObject = -2;
180 
181 // CPU status
182 #define S7CpuStatusUnknown  0x00
183 #define S7CpuStatusRun      0x08
184 #define S7CpuStatusStop     0x04
185 
186 // ISO Errors
187 const longword errIsoConnect            = 0x00010000; // Connection error
188 const longword errIsoDisconnect         = 0x00020000; // Disconnect error
189 const longword errIsoInvalidPDU         = 0x00030000; // Bad format
190 const longword errIsoInvalidDataSize    = 0x00040000; // Bad Datasize passed to send/recv buffer is invalid
191 const longword errIsoNullPointer    	= 0x00050000; // Null passed as pointer
192 const longword errIsoShortPacket    	= 0x00060000; // A short packet received
193 const longword errIsoTooManyFragments   = 0x00070000; // Too many packets without EoT flag
194 const longword errIsoPduOverflow    	= 0x00080000; // The sum of fragments data exceded maximum packet size
195 const longword errIsoSendPacket         = 0x00090000; // An error occurred during send
196 const longword errIsoRecvPacket         = 0x000A0000; // An error occurred during recv
197 const longword errIsoInvalidParams    	= 0x000B0000; // Invalid TSAP params
198 const longword errIsoResvd_1            = 0x000C0000; // Unassigned
199 const longword errIsoResvd_2            = 0x000D0000; // Unassigned
200 const longword errIsoResvd_3            = 0x000E0000; // Unassigned
201 const longword errIsoResvd_4            = 0x000F0000; // Unassigned
202 
203 //------------------------------------------------------------------------------
204 //                                  PARAMS LIST
205 //------------------------------------------------------------------------------
206 const int p_u16_LocalPort  	    = 1;
207 const int p_u16_RemotePort 	    = 2;
208 const int p_i32_PingTimeout	    = 3;
209 const int p_i32_SendTimeout     = 4;
210 const int p_i32_RecvTimeout     = 5;
211 const int p_i32_WorkInterval    = 6;
212 const int p_u16_SrcRef          = 7;
213 const int p_u16_DstRef          = 8;
214 const int p_u16_SrcTSap         = 9;
215 const int p_i32_PDURequest      = 10;
216 const int p_i32_MaxClients      = 11;
217 const int p_i32_BSendTimeout    = 12;
218 const int p_i32_BRecvTimeout    = 13;
219 const int p_u32_RecoveryTime    = 14;
220 const int p_u32_KeepAliveTime   = 15;
221 
222 // Client/Partner Job status
223 const int JobComplete           = 0;
224 const int JobPending            = 1;
225 
226 //******************************************************************************
227 //                                   CLIENT
228 //******************************************************************************
229 
230 // Error codes
231 const longword errNegotiatingPDU            = 0x00100000;
232 const longword errCliInvalidParams          = 0x00200000;
233 const longword errCliJobPending             = 0x00300000;
234 const longword errCliTooManyItems           = 0x00400000;
235 const longword errCliInvalidWordLen         = 0x00500000;
236 const longword errCliPartialDataWritten     = 0x00600000;
237 const longword errCliSizeOverPDU            = 0x00700000;
238 const longword errCliInvalidPlcAnswer       = 0x00800000;
239 const longword errCliAddressOutOfRange      = 0x00900000;
240 const longword errCliInvalidTransportSize   = 0x00A00000;
241 const longword errCliWriteDataSizeMismatch  = 0x00B00000;
242 const longword errCliItemNotAvailable       = 0x00C00000;
243 const longword errCliInvalidValue           = 0x00D00000;
244 const longword errCliCannotStartPLC         = 0x00E00000;
245 const longword errCliAlreadyRun             = 0x00F00000;
246 const longword errCliCannotStopPLC          = 0x01000000;
247 const longword errCliCannotCopyRamToRom     = 0x01100000;
248 const longword errCliCannotCompress         = 0x01200000;
249 const longword errCliAlreadyStop            = 0x01300000;
250 const longword errCliFunNotAvailable        = 0x01400000;
251 const longword errCliUploadSequenceFailed   = 0x01500000;
252 const longword errCliInvalidDataSizeRecvd   = 0x01600000;
253 const longword errCliInvalidBlockType       = 0x01700000;
254 const longword errCliInvalidBlockNumber     = 0x01800000;
255 const longword errCliInvalidBlockSize       = 0x01900000;
256 const longword errCliDownloadSequenceFailed = 0x01A00000;
257 const longword errCliInsertRefused          = 0x01B00000;
258 const longword errCliDeleteRefused          = 0x01C00000;
259 const longword errCliNeedPassword           = 0x01D00000;
260 const longword errCliInvalidPassword        = 0x01E00000;
261 const longword errCliNoPasswordToSetOrClear = 0x01F00000;
262 const longword errCliJobTimeout             = 0x02000000;
263 const longword errCliPartialDataRead        = 0x02100000;
264 const longword errCliBufferTooSmall         = 0x02200000;
265 const longword errCliFunctionRefused        = 0x02300000;
266 const longword errCliDestroying             = 0x02400000;
267 const longword errCliInvalidParamNumber     = 0x02500000;
268 const longword errCliCannotChangeParam      = 0x02600000;
269 
270 const int MaxVars     = 20; // Max vars that can be transferred with MultiRead/MultiWrite
271 
272 // Client Connection Type
273 const word CONNTYPE_PG                      = 0x0001;  // Connect to the PLC as a PG
274 const word CONNTYPE_OP                      = 0x0002;  // Connect to the PLC as an OP
275 const word CONNTYPE_BASIC                   = 0x0003;  // Basic connection
276 
277 // Area ID
278 const byte S7AreaPE   =	0x81;
279 const byte S7AreaPA   =	0x82;
280 const byte S7AreaMK   =	0x83;
281 const byte S7AreaDB   =	0x84;
282 const byte S7AreaCT   =	0x1C;
283 const byte S7AreaTM   =	0x1D;
284 
285 // Word Length
286 const int S7WLBit     = 0x01;
287 const int S7WLByte    = 0x02;
288 const int S7WLWord    = 0x04;
289 const int S7WLDWord   = 0x06;
290 const int S7WLReal    = 0x08;
291 const int S7WLCounter = 0x1C;
292 const int S7WLTimer   = 0x1D;
293 
294 // Block type
295 const byte Block_OB   = 0x38;
296 const byte Block_DB   = 0x41;
297 const byte Block_SDB  = 0x42;
298 const byte Block_FC   = 0x43;
299 const byte Block_SFC  = 0x44;
300 const byte Block_FB   = 0x45;
301 const byte Block_SFB  = 0x46;
302 
303 // Sub Block Type
304 const byte SubBlk_OB  = 0x08;
305 const byte SubBlk_DB  = 0x0A;
306 const byte SubBlk_SDB = 0x0B;
307 const byte SubBlk_FC  = 0x0C;
308 const byte SubBlk_SFC = 0x0D;
309 const byte SubBlk_FB  = 0x0E;
310 const byte SubBlk_SFB = 0x0F;
311 
312 // Block languages
313 const byte BlockLangAWL       = 0x01;
314 const byte BlockLangKOP       = 0x02;
315 const byte BlockLangFUP       = 0x03;
316 const byte BlockLangSCL       = 0x04;
317 const byte BlockLangDB        = 0x05;
318 const byte BlockLangGRAPH     = 0x06;
319 
320 // Read/Write Multivars
321 typedef struct{
322    int   Area;
323    int   WordLen;
324    int   Result;
325    int   DBNumber;
326    int   Start;
327    int   Amount;
328    void  *pdata;
329 } TS7DataItem, *PS7DataItem;
330 
331 //typedef int TS7ResultItems[MaxVars];
332 //typedef TS7ResultItems *PS7ResultItems;
333 
334 // List Blocks
335 typedef struct {
336    int OBCount;
337    int FBCount;
338    int FCCount;
339    int SFBCount;
340    int SFCCount;
341    int DBCount;
342    int SDBCount;
343 } TS7BlocksList, *PS7BlocksList;
344 
345 // Blocks info
346 typedef struct {
347    int BlkType;    // Block Type (OB, DB)
348    int BlkNumber;  // Block number
349    int BlkLang;    // Block Language
350    int BlkFlags;   // Block flags
351    int MC7Size;    // The real size in bytes
352    int LoadSize;   // Load memory size
353    int LocalData;  // Local data
354    int SBBLength;  // SBB Length
355    int CheckSum;   // Checksum
356    int Version;    // Block version
357    // Chars info
358    char CodeDate[11]; // Code date
359    char IntfDate[11]; // Interface date
360    char Author[9];    // Author
361    char Family[9];    // Family
362    char Header[9];    // Header
363 } TS7BlockInfo, *PS7BlockInfo ;
364 
365 typedef word TS7BlocksOfType[0x2000];
366 typedef TS7BlocksOfType *PS7BlocksOfType;
367 
368 // Order code
369 typedef struct {
370    char Code[21];
371    byte V1;
372    byte V2;
373    byte V3;
374 } TS7OrderCode, *PS7OrderCode;
375 
376 // CPU Info
377 typedef struct {
378    char ModuleTypeName[33];
379    char SerialNumber[25];
380    char ASName[25];
381    char Copyright[27];
382    char ModuleName[25];
383 } TS7CpuInfo, *PS7CpuInfo;
384 
385 // CP Info
386 typedef struct {
387    int MaxPduLengt;
388    int MaxConnections;
389    int MaxMpiRate;
390    int MaxBusRate;
391 } TS7CpInfo, *PS7CpInfo;
392 
393 // See §33.1 of "System Software for S7-300/400 System and Standard Functions"
394 // and see SFC51 description too
395 typedef struct {
396    word LENTHDR;
397    word N_DR;
398 } SZL_HEADER, *PSZL_HEADER;
399 
400 typedef struct {
401    SZL_HEADER Header;
402    byte Data[0x4000-4];
403 } TS7SZL, *PS7SZL;
404 
405 // SZL List of available SZL IDs : same as SZL but List items are big-endian adjusted
406 typedef struct {
407    SZL_HEADER Header;
408    word List[0x2000-2];
409 } TS7SZLList, *PS7SZLList;
410 
411 // See §33.19 of "System Software for S7-300/400 System and Standard Functions"
412 typedef struct {
413    word  sch_schal;
414    word  sch_par;
415    word  sch_rel;
416    word  bart_sch;
417    word  anl_sch;
418 } TS7Protection, *PS7Protection;
419 
420 // Client completion callback
421 typedef void (S7API *pfn_CliCompletion) (void *usrPtr, int opCode, int opResult);
422 //------------------------------------------------------------------------------
423 //  Import prototypes
424 //------------------------------------------------------------------------------
425 S7Object S7API Cli_Create();
426 void S7API Cli_Destroy(S7Object *Client);
427 int S7API Cli_ConnectTo(S7Object Client, const char *Address, int Rack, int Slot);
428 int S7API Cli_SetConnectionParams(S7Object Client, const char *Address, word LocalTSAP, word RemoteTSAP);
429 int S7API Cli_SetConnectionType(S7Object Client, word ConnectionType);
430 int S7API Cli_Connect(S7Object Client);
431 int S7API Cli_Disconnect(S7Object Client);
432 int S7API Cli_GetParam(S7Object Client, int ParamNumber, void *pValue);
433 int S7API Cli_SetParam(S7Object Client, int ParamNumber, void *pValue);
434 int S7API Cli_SetAsCallback(S7Object Client, pfn_CliCompletion pCompletion, void *usrPtr);
435 // Data I/O main functions
436 int S7API Cli_ReadArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
437 int S7API Cli_WriteArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
438 int S7API Cli_ReadMultiVars(S7Object Client, PS7DataItem Item, int ItemsCount);
439 int S7API Cli_WriteMultiVars(S7Object Client, PS7DataItem Item, int ItemsCount);
440 // Data I/O Lean functions
441 int S7API Cli_DBRead(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
442 int S7API Cli_DBWrite(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
443 int S7API Cli_MBRead(S7Object Client, int Start, int Size, void *pUsrData);
444 int S7API Cli_MBWrite(S7Object Client, int Start, int Size, void *pUsrData);
445 int S7API Cli_EBRead(S7Object Client, int Start, int Size, void *pUsrData);
446 int S7API Cli_EBWrite(S7Object Client, int Start, int Size, void *pUsrData);
447 int S7API Cli_ABRead(S7Object Client, int Start, int Size, void *pUsrData);
448 int S7API Cli_ABWrite(S7Object Client, int Start, int Size, void *pUsrData);
449 int S7API Cli_TMRead(S7Object Client, int Start, int Amount, void *pUsrData);
450 int S7API Cli_TMWrite(S7Object Client, int Start, int Amount, void *pUsrData);
451 int S7API Cli_CTRead(S7Object Client, int Start, int Amount, void *pUsrData);
452 int S7API Cli_CTWrite(S7Object Client, int Start, int Amount, void *pUsrData);
453 // Directory functions
454 int S7API Cli_ListBlocks(S7Object Client, TS7BlocksList *pUsrData);
455 int S7API Cli_GetAgBlockInfo(S7Object Client, int BlockType, int BlockNum, TS7BlockInfo *pUsrData);
456 int S7API Cli_GetPgBlockInfo(S7Object Client, void *pBlock, TS7BlockInfo *pUsrData, int Size);
457 int S7API Cli_ListBlocksOfType(S7Object Client, int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
458 // Blocks functions
459 int S7API Cli_Upload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
460 int S7API Cli_FullUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
461 int S7API Cli_Download(S7Object Client, int BlockNum, void *pUsrData, int Size);
462 int S7API Cli_Delete(S7Object Client, int BlockType, int BlockNum);
463 int S7API Cli_DBGet(S7Object Client, int DBNumber, void *pUsrData, int *Size);
464 int S7API Cli_DBFill(S7Object Client, int DBNumber, int FillChar);
465 // Date/Time functions
466 int S7API Cli_GetPlcDateTime(S7Object Client, tm *DateTime);
467 int S7API Cli_SetPlcDateTime(S7Object Client, tm *DateTime);
468 int S7API Cli_SetPlcSystemDateTime(S7Object Client);
469 // System Info functions
470 int S7API Cli_GetOrderCode(S7Object Client, TS7OrderCode *pUsrData);
471 int S7API Cli_GetCpuInfo(S7Object Client, TS7CpuInfo *pUsrData);
472 int S7API Cli_GetCpInfo(S7Object Client, TS7CpInfo *pUsrData);
473 int S7API Cli_ReadSZL(S7Object Client, int ID, int Index, TS7SZL *pUsrData, int *Size);
474 int S7API Cli_ReadSZLList(S7Object Client, TS7SZLList *pUsrData, int *ItemsCount);
475 // Control functions
476 int S7API Cli_PlcHotStart(S7Object Client);
477 int S7API Cli_PlcColdStart(S7Object Client);
478 int S7API Cli_PlcStop(S7Object Client);
479 int S7API Cli_CopyRamToRom(S7Object Client, int Timeout);
480 int S7API Cli_Compress(S7Object Client, int Timeout);
481 int S7API Cli_GetPlcStatus(S7Object Client, int *Status);
482 // Security functions
483 int S7API Cli_GetProtection(S7Object Client, TS7Protection *pUsrData);
484 int S7API Cli_SetSessionPassword(S7Object Client, char *Password);
485 int S7API Cli_ClearSessionPassword(S7Object Client);
486 // Low level
487 int S7API Cli_IsoExchangeBuffer(S7Object Client, void *pUsrData, int *Size);
488 // Misc
489 int S7API Cli_GetExecTime(S7Object Client, int *Time);
490 int S7API Cli_GetLastError(S7Object Client, int *LastError);
491 int S7API Cli_GetPduLength(S7Object Client, int *Requested, int *Negotiated);
492 int S7API Cli_ErrorText(int Error, char *Text, int TextLen);
493 // 1.1.0
494 int S7API Cli_GetConnected(S7Object Client, int *Connected);
495 //------------------------------------------------------------------------------
496 //  Async functions
497 //------------------------------------------------------------------------------
498 int S7API Cli_AsReadArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
499 int S7API Cli_AsWriteArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
500 int S7API Cli_AsDBRead(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
501 int S7API Cli_AsDBWrite(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
502 int S7API Cli_AsMBRead(S7Object Client, int Start, int Size, void *pUsrData);
503 int S7API Cli_AsMBWrite(S7Object Client, int Start, int Size, void *pUsrData);
504 int S7API Cli_AsEBRead(S7Object Client, int Start, int Size, void *pUsrData);
505 int S7API Cli_AsEBWrite(S7Object Client, int Start, int Size, void *pUsrData);
506 int S7API Cli_AsABRead(S7Object Client, int Start, int Size, void *pUsrData);
507 int S7API Cli_AsABWrite(S7Object Client, int Start, int Size, void *pUsrData);
508 int S7API Cli_AsTMRead(S7Object Client, int Start, int Amount, void *pUsrData);
509 int S7API Cli_AsTMWrite(S7Object Client, int Start, int Amount, void *pUsrData);
510 int S7API Cli_AsCTRead(S7Object Client, int Start, int Amount, void *pUsrData);
511 int S7API Cli_AsCTWrite(S7Object Client, int Start, int Amount, void *pUsrData);
512 int S7API Cli_AsListBlocksOfType(S7Object Client, int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
513 int S7API Cli_AsReadSZL(S7Object Client, int ID, int Index, TS7SZL *pUsrData, int *Size);
514 int S7API Cli_AsReadSZLList(S7Object Client, TS7SZLList *pUsrData, int *ItemsCount);
515 int S7API Cli_AsUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
516 int S7API Cli_AsFullUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
517 int S7API Cli_AsDownload(S7Object Client, int BlockNum, void *pUsrData, int Size);
518 int S7API Cli_AsCopyRamToRom(S7Object Client, int Timeout);
519 int S7API Cli_AsCompress(S7Object Client, int Timeout);
520 int S7API Cli_AsDBGet(S7Object Client, int DBNumber, void *pUsrData, int *Size);
521 int S7API Cli_AsDBFill(S7Object Client, int DBNumber, int FillChar);
522 int S7API Cli_CheckAsCompletion(S7Object Client, int *opResult);
523 int S7API Cli_WaitAsCompletion(S7Object Client, int Timeout);
524 
525 //******************************************************************************
526 //                                   SERVER
527 //******************************************************************************
528 
529 const int mkEvent = 0;
530 const int mkLog   = 1;
531 
532 // Server Area ID  (use with Register/unregister - Lock/unlock Area)
533 const int srvAreaPE = 0;
534 const int srvAreaPA = 1;
535 const int srvAreaMK = 2;
536 const int srvAreaCT = 3;
537 const int srvAreaTM = 4;
538 const int srvAreaDB = 5;
539 
540 // Errors
541 const longword errSrvCannotStart        = 0x00100000; // Server cannot start
542 const longword errSrvDBNullPointer      = 0x00200000; // Passed null as PData
543 const longword errSrvAreaAlreadyExists  = 0x00300000; // Area Re-registration
544 const longword errSrvUnknownArea        = 0x00400000; // Unknown area
545 const longword errSrvInvalidParams      = 0x00500000; // Invalid param(s) supplied
546 const longword errSrvTooManyDB          = 0x00600000; // Cannot register DB
547 const longword errSrvInvalidParamNumber = 0x00700000; // Invalid param (srv_get/set_param)
548 const longword errSrvCannotChangeParam  = 0x00800000; // Cannot change because running
549 
550 // TCP Server Event codes
551 const longword evcServerStarted       = 0x00000001;
552 const longword evcServerStopped       = 0x00000002;
553 const longword evcListenerCannotStart = 0x00000004;
554 const longword evcClientAdded         = 0x00000008;
555 const longword evcClientRejected      = 0x00000010;
556 const longword evcClientNoRoom        = 0x00000020;
557 const longword evcClientException     = 0x00000040;
558 const longword evcClientDisconnected  = 0x00000080;
559 const longword evcClientTerminated    = 0x00000100;
560 const longword evcClientsDropped      = 0x00000200;
561 const longword evcReserved_00000400   = 0x00000400; // actually unused
562 const longword evcReserved_00000800   = 0x00000800; // actually unused
563 const longword evcReserved_00001000   = 0x00001000; // actually unused
564 const longword evcReserved_00002000   = 0x00002000; // actually unused
565 const longword evcReserved_00004000   = 0x00004000; // actually unused
566 const longword evcReserved_00008000   = 0x00008000; // actually unused
567 // S7 Server Event Code
568 const longword evcPDUincoming  	      = 0x00010000;
569 const longword evcDataRead            = 0x00020000;
570 const longword evcDataWrite    	      = 0x00040000;
571 const longword evcNegotiatePDU        = 0x00080000;
572 const longword evcReadSZL             = 0x00100000;
573 const longword evcClock               = 0x00200000;
574 const longword evcUpload              = 0x00400000;
575 const longword evcDownload            = 0x00800000;
576 const longword evcDirectory           = 0x01000000;
577 const longword evcSecurity            = 0x02000000;
578 const longword evcControl             = 0x04000000;
579 const longword evcReserved_08000000   = 0x08000000; // actually unused
580 const longword evcReserved_10000000   = 0x10000000; // actually unused
581 const longword evcReserved_20000000   = 0x20000000; // actually unused
582 const longword evcReserved_40000000   = 0x40000000; // actually unused
583 const longword evcReserved_80000000   = 0x80000000; // actually unused
584 // Masks to enable/disable all events
585 const longword evcAll                 = 0xFFFFFFFF;
586 const longword evcNone                = 0x00000000;
587 // Event SubCodes
588 const word evsUnknown                 = 0x0000;
589 const word evsStartUpload             = 0x0001;
590 const word evsStartDownload           = 0x0001;
591 const word evsGetBlockList            = 0x0001;
592 const word evsStartListBoT            = 0x0002;
593 const word evsListBoT                 = 0x0003;
594 const word evsGetBlockInfo            = 0x0004;
595 const word evsGetClock                = 0x0001;
596 const word evsSetClock                = 0x0002;
597 const word evsSetPassword             = 0x0001;
598 const word evsClrPassword             = 0x0002;
599 // Event Params : functions group
600 const word grProgrammer               = 0x0041;
601 const word grCyclicData               = 0x0042;
602 const word grBlocksInfo               = 0x0043;
603 const word grSZL                      = 0x0044;
604 const word grPassword                 = 0x0045;
605 const word grBSend                    = 0x0046;
606 const word grClock                    = 0x0047;
607 const word grSecurity                 = 0x0045;
608 // Event Params : control codes
609 const word CodeControlUnknown         = 0x0000;
610 const word CodeControlColdStart       = 0x0001;
611 const word CodeControlWarmStart       = 0x0002;
612 const word CodeControlStop            = 0x0003;
613 const word CodeControlCompress        = 0x0004;
614 const word CodeControlCpyRamRom       = 0x0005;
615 const word CodeControlInsDel          = 0x0006;
616 // Event Result
617 const word evrNoError                 = 0x0000;
618 const word evrFragmentRejected        = 0x0001;
619 const word evrMalformedPDU            = 0x0002;
620 const word evrSparseBytes             = 0x0003;
621 const word evrCannotHandlePDU         = 0x0004;
622 const word evrNotImplemented          = 0x0005;
623 const word evrErrException            = 0x0006;
624 const word evrErrAreaNotFound         = 0x0007;
625 const word evrErrOutOfRange           = 0x0008;
626 const word evrErrOverPDU              = 0x0009;
627 const word evrErrTransportSize        = 0x000A;
628 const word evrInvalidGroupUData       = 0x000B;
629 const word evrInvalidSZL              = 0x000C;
630 const word evrDataSizeMismatch        = 0x000D;
631 const word evrCannotUpload            = 0x000E;
632 const word evrCannotDownload          = 0x000F;
633 const word evrUploadInvalidID         = 0x0010;
634 const word evrResNotFound             = 0x0011;
635 
636 typedef struct{
637 	time_t EvtTime;    // Timestamp
638 	int EvtSender;     // Sender
639 	longword EvtCode;  // Event code
640 	word EvtRetCode;   // Event result
641 	word EvtParam1;    // Param 1 (if available)
642 	word EvtParam2;    // Param 2 (if available)
643 	word EvtParam3;    // Param 3 (if available)
644 	word EvtParam4;    // Param 4 (if available)
645 }TSrvEvent, *PSrvEvent;
646 
647 // Server Evants callback
648 typedef void (S7API *pfn_SrvCallBack)(void * usrPtr, PSrvEvent PEvent, int Size);
649 S7Object S7API Srv_Create();
650 void S7API Srv_Destroy(S7Object *Server);
651 int S7API Srv_GetParam(S7Object Server, int ParamNumber, void *pValue);
652 int S7API Srv_SetParam(S7Object Server, int ParamNumber, void *pValue);
653 int S7API Srv_StartTo(S7Object Server, const char *Address);
654 int S7API Srv_Start(S7Object Server);
655 int S7API Srv_Stop(S7Object Server);
656 int S7API Srv_RegisterArea(S7Object Server, int AreaCode, word Index, void *pUsrData, int Size);
657 int S7API Srv_UnregisterArea(S7Object Server, int AreaCode, word Index);
658 int S7API Srv_LockArea(S7Object Server, int AreaCode, word Index);
659 int S7API Srv_UnlockArea(S7Object Server, int AreaCode, word Index);
660 int S7API Srv_GetStatus(S7Object Server, int *ServerStatus, int *CpuStatus, int *ClientsCount);
661 int S7API Srv_SetCpuStatus(S7Object Server, int CpuStatus);
662 int S7API Srv_ClearEvents(S7Object Server);
663 int S7API Srv_PickEvent(S7Object Server, TSrvEvent *pEvent, int *EvtReady);
664 int S7API Srv_GetMask(S7Object Server, int MaskKind, longword *Mask);
665 int S7API Srv_SetMask(S7Object Server, int MaskKind, longword Mask);
666 int S7API Srv_SetEventsCallback(S7Object Server, pfn_SrvCallBack pCallback, void *usrPtr);
667 int S7API Srv_SetReadEventsCallback(S7Object Server, pfn_SrvCallBack pCallback, void *usrPtr);
668 int S7API Srv_EventText(TSrvEvent *Event, char *Text, int TextLen);
669 int S7API Srv_ErrorText(int Error, char *Text, int TextLen);
670 
671 //******************************************************************************
672 //                                   PARTNER
673 //******************************************************************************
674 
675 // Status
676 const int par_stopped         = 0;   // stopped
677 const int par_connecting      = 1;   // running and active connecting
678 const int par_waiting         = 2;   // running and waiting for a connection
679 const int par_linked          = 3;   // running and connected : linked
680 const int par_sending         = 4;   // sending data
681 const int par_receiving       = 5;   // receiving data
682 const int par_binderror       = 6;   // error starting passive server
683 
684 // Errors
685 const longword errParAddressInUse       = 0x00200000;
686 const longword errParNoRoom             = 0x00300000;
687 const longword errServerNoRoom          = 0x00400000;
688 const longword errParInvalidParams      = 0x00500000;
689 const longword errParNotLinked          = 0x00600000;
690 const longword errParBusy               = 0x00700000;
691 const longword errParFrameTimeout       = 0x00800000;
692 const longword errParInvalidPDU         = 0x00900000;
693 const longword errParSendTimeout        = 0x00A00000;
694 const longword errParRecvTimeout        = 0x00B00000;
695 const longword errParSendRefused        = 0x00C00000;
696 const longword errParNegotiatingPDU     = 0x00D00000;
697 const longword errParSendingBlock       = 0x00E00000;
698 const longword errParRecvingBlock       = 0x00F00000;
699 const longword errParBindError          = 0x01000000;
700 const longword errParDestroying         = 0x01100000;
701 const longword errParInvalidParamNumber = 0x01200000; // Invalid param (par_get/set_param)
702 const longword errParCannotChangeParam  = 0x01300000; // Cannot change because running
703 const longword errParBufferTooSmall     = 0x01400000; // Raised by LabVIEW wrapper
704 
705 // Brecv Data incoming Callback
706 typedef void (S7API *pfn_ParRecvCallBack)(void * usrPtr, int opResult, longword R_ID, void *pData, int Size);
707 // BSend Completion Callback
708 typedef void (S7API *pfn_ParSendCompletion)(void * usrPtr, int opResult);
709 
710 S7Object S7API Par_Create(int Active);
711 void S7API Par_Destroy(S7Object *Partner);
712 int S7API Par_GetParam(S7Object Partner, int ParamNumber, void *pValue);
713 int S7API Par_SetParam(S7Object Partner, int ParamNumber, void *pValue);
714 int S7API Par_StartTo(S7Object Partner, const char *LocalAddress, const char *RemoteAddress,
715     word LocTsap, word RemTsap);
716 int S7API Par_Start(S7Object Partner);
717 int S7API Par_Stop(S7Object Partner);
718 // BSend
719 int S7API Par_BSend(S7Object Partner, longword R_ID, void *pUsrData, int Size);
720 int S7API Par_AsBSend(S7Object Partner, longword R_ID, void *pUsrData, int Size);
721 int S7API Par_CheckAsBSendCompletion(S7Object Partner, int *opResult);
722 int S7API Par_WaitAsBSendCompletion(S7Object Partner, longword Timeout);
723 int S7API Par_SetSendCallback(S7Object Partner, pfn_ParSendCompletion pCompletion, void *usrPtr);
724 // BRecv
725 int S7API Par_BRecv(S7Object Partner, longword *R_ID, void *pData, int *Size, longword Timeout);
726 int S7API Par_CheckAsBRecvCompletion(S7Object Partner, int *opResult, longword *R_ID,
727 	void *pData, int *Size);
728 int S7API Par_SetRecvCallback(S7Object Partner, pfn_ParRecvCallBack pCompletion, void *usrPtr);
729 // Stat
730 int S7API Par_GetTimes(S7Object Partner, longword *SendTime, longword *RecvTime);
731 int S7API Par_GetStats(S7Object Partner, longword *BytesSent, longword *BytesRecv,
732 	longword *SendErrors, longword *RecvErrors);
733 int S7API Par_GetLastError(S7Object Partner, int *LastError);
734 int S7API Par_GetStatus(S7Object Partner, int *Status);
735 int S7API Par_ErrorText(int Error, char *Text, int TextLen);
736 
737 //******************************************************************************
738 //                           HELPER DATA ACCESS FUNCTIONS
739 //******************************************************************************
740 // GET
741 bool GetBitAt(void *Buffer, int Pos, int Bit);
742 byte GetByteAt(void *Buffer, int Pos);
743 word GetWordAt(void *Buffer, int Pos);
744 smallint GetIntAt(void *Buffer, int Pos);
745 longword GetDWordAt(void *Buffer, int Pos);
746 longint GetDIntAt(void *Buffer, int Pos);
747 float GetRealAt(void *Buffer, int Pos);
748 struct tm GetDateTimeAt(void *Buffer, int Pos);
749 // SET
750 void SetBitAt(void *Buffer, int Pos, int Bit, bool Value);
751 void SetByteAt(void *Buffer, int Pos, byte Value);
752 void SetWordAt(void *Buffer, int Pos, word Value);
753 void SetIntAt(void *Buffer, int Pos, smallint Value);
754 void SetDWordAt(void *Buffer, int Pos, longword Value);
755 void SetDIntAt(void *Buffer, int Pos, longint Value);
756 void SetRealAt(void *Buffer, int Pos, float Value);
757 void SetDateTimeAt(void *Buffer, int Pos, tm Value);
758 
759 
760 #pragma pack()
761 #ifdef __cplusplus
762  }
763 #endif // __cplusplus
764 
765 #ifdef __cplusplus
766 
767 //******************************************************************************
768 //                           CLIENT CLASS DEFINITION
769 //******************************************************************************
770 class TS7Client
771 {
772 private:
773     S7Object Client;
774 public:
775 	TS7Client();
776 	~TS7Client();
777     // Control functions
778     int Connect();
779     int ConnectTo(const char *RemAddress, int Rack, int Slot);
780     int SetConnectionParams(const char *RemAddress, word LocalTSAP, word RemoteTSAP);
781     int SetConnectionType(word ConnectionType);
782     int Disconnect();
783     int GetParam(int ParamNumber, void *pValue);
784     int SetParam(int ParamNumber, void *pValue);
785     // Data I/O Main functions
786     int ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
787     int WriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
788     int ReadMultiVars(PS7DataItem Item, int ItemsCount);
789     int WriteMultiVars(PS7DataItem Item, int ItemsCount);
790     // Data I/O Lean functions
791     int DBRead(int DBNumber, int Start, int Size, void *pUsrData);
792     int DBWrite(int DBNumber, int Start, int Size, void *pUsrData);
793     int MBRead(int Start, int Size, void *pUsrData);
794     int MBWrite(int Start, int Size, void *pUsrData);
795     int EBRead(int Start, int Size, void *pUsrData);
796     int EBWrite(int Start, int Size, void *pUsrData);
797     int ABRead(int Start, int Size, void *pUsrData);
798     int ABWrite(int Start, int Size, void *pUsrData);
799     int TMRead(int Start, int Amount, void *pUsrData);
800     int TMWrite(int Start, int Amount, void *pUsrData);
801     int CTRead(int Start, int Amount, void *pUsrData);
802     int CTWrite(int Start, int Amount, void *pUsrData);
803     // Directory functions
804     int ListBlocks(PS7BlocksList pUsrData);
805     int GetAgBlockInfo(int BlockType, int BlockNum, PS7BlockInfo pUsrData);
806     int GetPgBlockInfo(void *pBlock, PS7BlockInfo pUsrData, int Size);
807     int ListBlocksOfType(int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
808     // Blocks functions
809     int Upload(int BlockType, int BlockNum, void *pUsrData, int *Size);
810     int FullUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
811     int Download(int BlockNum, void *pUsrData, int Size);
812     int Delete(int BlockType, int BlockNum);
813     int DBGet(int DBNumber, void *pUsrData, int *Size);
814     int DBFill(int DBNumber, int FillChar);
815     // Date/Time functions
816     int GetPlcDateTime(tm *DateTime);
817     int SetPlcDateTime(tm *DateTime);
818     int SetPlcSystemDateTime();
819     // System Info functions
820     int GetOrderCode(PS7OrderCode pUsrData);
821     int GetCpuInfo(PS7CpuInfo pUsrData);
822     int GetCpInfo(PS7CpInfo pUsrData);
823 	int ReadSZL(int ID, int Index, PS7SZL pUsrData, int *Size);
824 	int ReadSZLList(PS7SZLList pUsrData, int *ItemsCount);
825 	// Control functions
826 	int PlcHotStart();
827 	int PlcColdStart();
828 	int PlcStop();
829 	int CopyRamToRom(int Timeout);
830 	int Compress(int Timeout);
831 	// Security functions
832 	int GetProtection(PS7Protection pUsrData);
833 	int SetSessionPassword(char *Password);
834 	int ClearSessionPassword();
835 	// Properties
836 	int ExecTime();
837 	int LastError();
838 	int PDURequested();
839 	int PDULength();
840 	int PlcStatus();
841 	bool Connected();
842 	// Async functions
843 	int SetAsCallback(pfn_CliCompletion pCompletion, void *usrPtr);
844 	bool CheckAsCompletion(int *opResult);
845 	int WaitAsCompletion(longword Timeout);
846 	int AsReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
847 	int AsWriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
848 	int AsListBlocksOfType(int BlockType, PS7BlocksOfType pUsrData, int *ItemsCount);
849 	int AsReadSZL(int ID, int Index, PS7SZL pUsrData, int *Size);
850 	int AsReadSZLList(PS7SZLList pUsrData, int *ItemsCount);
851 	int AsUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
852 	int AsFullUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
853 	int AsDownload(int BlockNum, void *pUsrData,  int Size);
854 	int AsCopyRamToRom(int Timeout);
855 	int AsCompress(int Timeout);
856 	int AsDBRead(int DBNumber, int Start, int Size, void *pUsrData);
857 	int AsDBWrite(int DBNumber, int Start, int Size, void *pUsrData);
858 	int AsMBRead(int Start, int Size, void *pUsrData);
859 	int AsMBWrite(int Start, int Size, void *pUsrData);
860 	int AsEBRead(int Start, int Size, void *pUsrData);
861 	int AsEBWrite(int Start, int Size, void *pUsrData);
862 	int AsABRead(int Start, int Size, void *pUsrData);
863 	int AsABWrite(int Start, int Size, void *pUsrData);
864     int AsTMRead(int Start, int Amount, void *pUsrData);
865     int AsTMWrite(int Start, int Amount, void *pUsrData);
866     int AsCTRead(int Start, int Amount, void *pUsrData);
867 	int AsCTWrite(int Start, int Amount, void *pUsrData);
868     int AsDBGet(int DBNumber, void *pUsrData, int *Size);
869 	int AsDBFill(int DBNumber, int FillChar);
870 };
871 typedef TS7Client *PS7Client;
872 //******************************************************************************
873 //                           SERVER CLASS DEFINITION
874 //******************************************************************************
875 class TS7Server
876 {
877 private:
878     S7Object Server;
879 public:
880     TS7Server();
881     ~TS7Server();
882     // Control
883     int Start();
884     int StartTo(const char *Address);
885     int Stop();
886     int GetParam(int ParamNumber, void *pValue);
887     int SetParam(int ParamNumber, void *pValue);
888     // Events
889     int SetEventsCallback(pfn_SrvCallBack PCallBack, void *UsrPtr);
890     int SetReadEventsCallback(pfn_SrvCallBack PCallBack, void *UsrPtr);
891     bool PickEvent(TSrvEvent *pEvent);
892     void ClearEvents();
893     longword GetEventsMask();
894     longword GetLogMask();
895     void SetEventsMask(longword Mask);
896     void SetLogMask(longword Mask);
897     // Resources
898     int RegisterArea(int AreaCode, word Index, void *pUsrData, word Size);
899     int UnregisterArea(int AreaCode, word Index);
900     int LockArea(int AreaCode, word Index);
901     int UnlockArea(int AreaCode, word Index);
902     // Properties
903     int ServerStatus();
904     int GetCpuStatus();
905     int SetCpuStatus(int Status);
906 	int ClientsCount();
907 };
908 typedef TS7Server *PS7Server;
909 
910 //******************************************************************************
911 //                          PARTNER CLASS DEFINITION
912 //******************************************************************************
913 class TS7Partner
914 {
915 private:
916 	S7Object Partner; // Partner Handle
917 public:
918 	TS7Partner(bool Active);
919 	~TS7Partner();
920 	// Control
921 	int GetParam(int ParamNumber, void *pValue);
922 	int SetParam(int ParamNumber, void *pValue);
923 	int Start();
924 	int StartTo(const char *LocalAddress,
925 				const char *RemoteAddress,
926 				int LocalTSAP,
927 				int RemoteTSAP);
928 	int Stop();
929 	// Data I/O functions : BSend
930 	int BSend(longword R_ID, void *pUsrData, int Size);
931 	int AsBSend(longword R_ID, void *pUsrData, int Size);
932 	bool CheckAsBSendCompletion(int *opResult);
933 	int WaitAsBSendCompletion(longword Timeout);
934 	int SetSendCallback(pfn_ParSendCompletion pCompletion, void *usrPtr);
935 	// Data I/O functions : BRecv
936 	int BRecv(longword *R_ID, void *pUsrData, int *Size, longword Timeout);
937 	bool CheckAsBRecvCompletion(int *opResult, longword *R_ID, void *pUsrData, int *Size);
938 	int SetRecvCallback(pfn_ParRecvCallBack pCallback, void *usrPtr);
939 	// Properties
940 	int Status();
941 	int LastError();
942 	int GetTimes(longword *SendTime, longword *RecvTime);
943 	int GetStats(longword *BytesSent,
944 				 longword *BytesRecv,
945 				 longword *ErrSend,
946 				 longword *ErrRecv);
947 	bool Linked();
948 };
949 typedef TS7Partner *PS7Partner;
950 //******************************************************************************
951 //                               TEXT ROUTINES
952 // Only for C++, for pure C use xxx_ErrorText() which uses *char
953 //******************************************************************************
954 #define TextLen 1024
955 
956 // String type
957 // Here we define generic TextString (by default mapped onto std::string).
958 // So you can change it if needed (Unicodestring, Ansistring etc...)
959 
960 typedef std::string TextString;
961 
962 TextString CliErrorText(int Error);
963 TextString SrvErrorText(int Error);
964 TextString ParErrorText(int Error);
965 TextString SrvEventText(TSrvEvent *Event);
966 
967 
968 #endif // __cplusplus
969 #endif // snap7_h
970