1 /*=============================================================================|
2 |  PROJECT SNAP7                                                         1.4.0 |
3 |==============================================================================|
4 |  Copyright (C) 2013, 2014, 2015 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# Interface classes.                                                       |
28 |                                                                              |
29 |=============================================================================*/
30 using System;
31 using System.Collections.Generic;
32 using System.Runtime.InteropServices;
33 using System.Text;
34 
35 namespace Snap7
36 {
37 
38     public class S7Consts
39     {
40         #if __MonoCS__  // Assuming that we are using Unix release of Mono (otherwise modify it)
41             public const string Snap7LibName = "libsnap7.so";
42         #else
43             public const string Snap7LibName = "snap7.dll";
44         #endif
45         //------------------------------------------------------------------------------
46         //                                  PARAMS LIST
47         //------------------------------------------------------------------------------
48         public static readonly Int32 p_u16_LocalPort     = 1;
49         public static readonly Int32 p_u16_RemotePort    = 2;
50         public static readonly Int32 p_i32_PingTimeout   = 3;
51         public static readonly Int32 p_i32_SendTimeout   = 4;
52         public static readonly Int32 p_i32_RecvTimeout   = 5;
53         public static readonly Int32 p_i32_WorkInterval  = 6;
54         public static readonly Int32 p_u16_SrcRef        = 7;
55         public static readonly Int32 p_u16_DstRef        = 8;
56         public static readonly Int32 p_u16_SrcTSap       = 9;
57         public static readonly Int32 p_i32_PDURequest    = 10;
58         public static readonly Int32 p_i32_MaxClients    = 11;
59         public static readonly Int32 p_i32_BSendTimeout  = 12;
60         public static readonly Int32 p_i32_BRecvTimeout  = 13;
61         public static readonly Int32 p_u32_RecoveryTime  = 14;
62         public static readonly Int32 p_u32_KeepAliveTime = 15;
63 
64         [StructLayout(LayoutKind.Sequential, Pack = 1)]
65         public struct S7Tag
66         {
67             public Int32 Area;
68             public Int32 DBNumber;
69             public Int32 Start;
70             public Int32 Elements;
71             public Int32 WordLen;
72         }
73     }
74 
75     public static class S7
76     {
77         #region [Help Functions]
78 
79         private static Int64 bias = 621355968000000000; // "decimicros" between 0001-01-01 00:00:00 and 1970-01-01 00:00:00
80 
BCDtoByte(byte B)81         private static int BCDtoByte(byte B)
82         {
83              return ((B >> 4) * 10) + (B & 0x0F);
84         }
85 
ByteToBCD(int Value)86         private static byte ByteToBCD(int Value)
87         {
88             return (byte)(((Value / 10) << 4) | (Value % 10));
89         }
90 
CopyFrom(byte[] Buffer, int Pos, int Size)91         private static byte[] CopyFrom(byte[] Buffer, int Pos, int Size)
92         {
93             byte[] Result=new byte[Size];
94             Array.Copy(Buffer, Pos, Result, 0, Size);
95             return Result;
96         }
97 
98         #region Get/Set the bit at Pos.Bit
GetBitAt(byte[] Buffer, int Pos, int Bit)99         public static bool GetBitAt(byte[] Buffer, int Pos, int Bit)
100         {
101             byte[] Mask = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
102             if (Bit < 0) Bit = 0;
103             if (Bit > 7) Bit = 7;
104             return (Buffer[Pos] & Mask[Bit]) != 0;
105         }
SetBitAt(ref byte[] Buffer, int Pos, int Bit, bool Value)106         public static void SetBitAt(ref byte[] Buffer, int Pos, int Bit, bool Value)
107         {
108             byte[] Mask = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
109             if (Bit < 0) Bit = 0;
110             if (Bit > 7) Bit = 7;
111 
112             if (Value)
113                 Buffer[Pos] = (byte)(Buffer[Pos] | Mask[Bit]);
114             else
115                 Buffer[Pos] = (byte)(Buffer[Pos] & ~Mask[Bit]);
116         }
117         #endregion
118 
119         #region Get/Set 8 bit signed value (S7 SInt) -128..127
GetSIntAt(byte[] Buffer, int Pos)120         public static int GetSIntAt(byte[] Buffer, int Pos)
121         {
122             int Value = Buffer[Pos];
123             if (Value < 128)
124                 return Value;
125             else
126                 return (int) (Value - 256);
127         }
SetSIntAt(byte[] Buffer, int Pos, int Value)128         public static void SetSIntAt(byte[] Buffer, int Pos, int Value)
129         {
130             if (Value < -128) Value = -128;
131             if (Value > 127) Value = 127;
132             Buffer[Pos] = (byte)Value;
133         }
134         #endregion
135 
136         #region Get/Set 16 bit signed value (S7 int) -32768..32767
GetIntAt(byte[] Buffer, int Pos)137         public static int GetIntAt(byte[] Buffer, int Pos)
138         {
139             return (short)((Buffer[Pos] << 8) | Buffer[Pos + 1]);
140         }
SetIntAt(byte[] Buffer, int Pos, Int16 Value)141         public static void SetIntAt(byte[] Buffer, int Pos, Int16 Value)
142         {
143             Buffer[Pos] = (byte)(Value >> 8);
144             Buffer[Pos + 1] = (byte)(Value & 0x00FF);
145         }
146         #endregion
147 
148         #region Get/Set 32 bit signed value (S7 DInt) -2147483648..2147483647
GetDIntAt(byte[] Buffer, int Pos)149         public static int GetDIntAt(byte[] Buffer, int Pos)
150         {
151             int Result;
152             Result = Buffer[Pos]; Result <<= 8;
153             Result += Buffer[Pos + 1]; Result <<= 8;
154             Result += Buffer[Pos + 2]; Result <<= 8;
155             Result += Buffer[Pos + 3];
156             return Result;
157         }
SetDIntAt(byte[] Buffer, int Pos, int Value)158         public static void SetDIntAt(byte[] Buffer, int Pos, int Value)
159         {
160             Buffer[Pos + 3] = (byte)(Value & 0xFF);
161             Buffer[Pos + 2] = (byte)((Value >> 8) & 0xFF);
162             Buffer[Pos + 1] = (byte)((Value >> 16) & 0xFF);
163             Buffer[Pos] = (byte)((Value >> 24) & 0xFF);
164         }
165         #endregion
166 
167         #region Get/Set 64 bit signed value (S7 LInt) -9223372036854775808..9223372036854775807
GetLIntAt(byte[] Buffer, int Pos)168         public static Int64 GetLIntAt(byte[] Buffer, int Pos)
169         {
170             Int64 Result;
171             Result = Buffer[Pos]; Result <<= 8;
172             Result += Buffer[Pos + 1]; Result <<= 8;
173             Result += Buffer[Pos + 2]; Result <<= 8;
174             Result += Buffer[Pos + 3]; Result <<= 8;
175             Result += Buffer[Pos + 4]; Result <<= 8;
176             Result += Buffer[Pos + 5]; Result <<= 8;
177             Result += Buffer[Pos + 6]; Result <<= 8;
178             Result += Buffer[Pos + 7];
179             return Result;
180         }
SetLIntAt(byte[] Buffer, int Pos, Int64 Value)181         public static void SetLIntAt(byte[] Buffer, int Pos, Int64 Value)
182         {
183             Buffer[Pos + 7] = (byte)(Value & 0xFF);
184             Buffer[Pos + 6] = (byte)((Value >> 8) & 0xFF);
185             Buffer[Pos + 5] = (byte)((Value >> 16) & 0xFF);
186             Buffer[Pos + 4] = (byte)((Value >> 24) & 0xFF);
187             Buffer[Pos + 3] = (byte)((Value >> 32) & 0xFF);
188             Buffer[Pos + 2] = (byte)((Value >> 40) & 0xFF);
189             Buffer[Pos + 1] = (byte)((Value >> 48) & 0xFF);
190             Buffer[Pos] = (byte)((Value >> 56) & 0xFF);
191         }
192         #endregion
193 
194         #region Get/Set 8 bit unsigned value (S7 USInt) 0..255
GetUSIntAt(byte[] Buffer, int Pos)195         public static byte GetUSIntAt(byte[] Buffer, int Pos)
196         {
197             return Buffer[Pos];
198         }
SetUSIntAt(byte[] Buffer, int Pos, byte Value)199         public static void SetUSIntAt(byte[] Buffer, int Pos, byte Value)
200         {
201             Buffer[Pos] = Value;
202         }
203         #endregion
204 
205         #region Get/Set 16 bit unsigned value (S7 UInt) 0..65535
GetUIntAt(byte[] Buffer, int Pos)206         public static UInt16 GetUIntAt(byte[] Buffer, int Pos)
207         {
208             return (UInt16)((Buffer[Pos] << 8) | Buffer[Pos + 1]);
209         }
SetUIntAt(byte[] Buffer, int Pos, UInt16 Value)210         public static void SetUIntAt(byte[] Buffer, int Pos, UInt16 Value)
211         {
212             Buffer[Pos] = (byte)(Value >> 8);
213             Buffer[Pos + 1] = (byte)(Value & 0x00FF);
214         }
215         #endregion
216 
217         #region Get/Set 32 bit unsigned value (S7 UDInt) 0..4294967296
GetUDIntAt(byte[] Buffer, int Pos)218         public static UInt32 GetUDIntAt(byte[] Buffer, int Pos)
219         {
220             UInt32 Result;
221             Result = Buffer[Pos]; Result <<= 8;
222             Result |= Buffer[Pos + 1]; Result <<= 8;
223             Result |= Buffer[Pos + 2]; Result <<= 8;
224             Result |= Buffer[Pos + 3];
225             return Result;
226         }
SetUDIntAt(byte[] Buffer, int Pos, UInt32 Value)227         public static void SetUDIntAt(byte[] Buffer, int Pos, UInt32 Value)
228         {
229             Buffer[Pos + 3] = (byte)(Value & 0xFF);
230             Buffer[Pos + 2] = (byte)((Value >> 8) & 0xFF);
231             Buffer[Pos + 1] = (byte)((Value >> 16) & 0xFF);
232             Buffer[Pos] = (byte)((Value >> 24) & 0xFF);
233         }
234         #endregion
235 
236         #region Get/Set 64 bit unsigned value (S7 ULint) 0..18446744073709551616
GetULIntAt(byte[] Buffer, int Pos)237         public static UInt64 GetULIntAt(byte[] Buffer, int Pos)
238         {
239             UInt64 Result;
240             Result = Buffer[Pos]; Result <<= 8;
241             Result |= Buffer[Pos + 1]; Result <<= 8;
242             Result |= Buffer[Pos + 2]; Result <<= 8;
243             Result |= Buffer[Pos + 3]; Result <<= 8;
244             Result |= Buffer[Pos + 4]; Result <<= 8;
245             Result |= Buffer[Pos + 5]; Result <<= 8;
246             Result |= Buffer[Pos + 6]; Result <<= 8;
247             Result |= Buffer[Pos + 7];
248             return Result;
249         }
SetULintAt(byte[] Buffer, int Pos, UInt64 Value)250         public static void SetULintAt(byte[] Buffer, int Pos, UInt64 Value)
251         {
252             Buffer[Pos + 7] = (byte)(Value & 0xFF);
253             Buffer[Pos + 6] = (byte)((Value >> 8) & 0xFF);
254             Buffer[Pos + 5] = (byte)((Value >> 16) & 0xFF);
255             Buffer[Pos + 4] = (byte)((Value >> 24) & 0xFF);
256             Buffer[Pos + 3] = (byte)((Value >> 32) & 0xFF);
257             Buffer[Pos + 2] = (byte)((Value >> 40) & 0xFF);
258             Buffer[Pos + 1] = (byte)((Value >> 48) & 0xFF);
259             Buffer[Pos] = (byte)((Value >> 56) & 0xFF);
260         }
261         #endregion
262 
263         #region Get/Set 8 bit word (S7 Byte) 16#00..16#FF
GetByteAt(byte[] Buffer, int Pos)264         public static byte GetByteAt(byte[] Buffer, int Pos)
265         {
266             return Buffer[Pos];
267         }
SetByteAt(byte[] Buffer, int Pos, byte Value)268         public static void SetByteAt(byte[] Buffer, int Pos, byte Value)
269         {
270             Buffer[Pos] = Value;
271         }
272         #endregion
273 
274         #region Get/Set 16 bit word (S7 Word) 16#0000..16#FFFF
GetWordAt(byte[] Buffer, int Pos)275         public static UInt16 GetWordAt(byte[] Buffer, int Pos)
276         {
277             return GetUIntAt(Buffer,Pos);
278         }
SetWordAt(byte[] Buffer, int Pos, UInt16 Value)279         public static void SetWordAt(byte[] Buffer, int Pos, UInt16 Value)
280         {
281             SetUIntAt(Buffer, Pos, Value);
282         }
283         #endregion
284 
285         #region Get/Set 32 bit word (S7 DWord) 16#00000000..16#FFFFFFFF
GetDWordAt(byte[] Buffer, int Pos)286         public static UInt32 GetDWordAt(byte[] Buffer, int Pos)
287         {
288             return GetUDIntAt(Buffer, Pos);
289         }
SetDWordAt(byte[] Buffer, int Pos, UInt32 Value)290         public static void SetDWordAt(byte[] Buffer, int Pos, UInt32 Value)
291         {
292             SetUDIntAt(Buffer, Pos, Value);
293         }
294         #endregion
295 
296         #region Get/Set 64 bit word (S7 LWord) 16#0000000000000000..16#FFFFFFFFFFFFFFFF
GetLWordAt(byte[] Buffer, int Pos)297         public static UInt64 GetLWordAt(byte[] Buffer, int Pos)
298         {
299             return GetULIntAt(Buffer, Pos);
300         }
SetLWordAt(byte[] Buffer, int Pos, UInt64 Value)301         public static void SetLWordAt(byte[] Buffer, int Pos, UInt64 Value)
302         {
303             SetULintAt(Buffer, Pos, Value);
304         }
305         #endregion
306 
307         #region Get/Set 32 bit floating point number (S7 Real) (Range of Single)
GetRealAt(byte[] Buffer, int Pos)308         public static Single GetRealAt(byte[] Buffer, int Pos)
309         {
310             UInt32 Value = GetUDIntAt(Buffer, Pos);
311             byte[] bytes = BitConverter.GetBytes(Value);
312             return BitConverter.ToSingle(bytes, 0);
313         }
SetRealAt(byte[] Buffer, int Pos, Single Value)314         public static void SetRealAt(byte[] Buffer, int Pos, Single Value)
315         {
316             byte[] FloatArray = BitConverter.GetBytes(Value);
317             Buffer[Pos] = FloatArray[3];
318             Buffer[Pos + 1] = FloatArray[2];
319             Buffer[Pos + 2] = FloatArray[1];
320             Buffer[Pos + 3] = FloatArray[0];
321         }
322         #endregion
323 
324         #region Get/Set 64 bit floating point number (S7 LReal) (Range of Double)
GetLRealAt(byte[] Buffer, int Pos)325         public static Double GetLRealAt(byte[] Buffer, int Pos)
326         {
327             UInt64 Value = GetULIntAt(Buffer, Pos);
328             byte[] bytes = BitConverter.GetBytes(Value);
329             return BitConverter.ToDouble(bytes, 0);
330         }
SetLRealAt(byte[] Buffer, int Pos, Double Value)331         public static void SetLRealAt(byte[] Buffer, int Pos, Double Value)
332         {
333             byte[] FloatArray = BitConverter.GetBytes(Value);
334             Buffer[Pos] = FloatArray[7];
335             Buffer[Pos + 1] = FloatArray[6];
336             Buffer[Pos + 2] = FloatArray[5];
337             Buffer[Pos + 3] = FloatArray[4];
338             Buffer[Pos + 4] = FloatArray[3];
339             Buffer[Pos + 5] = FloatArray[2];
340             Buffer[Pos + 6] = FloatArray[1];
341             Buffer[Pos + 7] = FloatArray[0];
342         }
343         #endregion
344 
345         #region Get/Set DateTime (S7 DATE_AND_TIME)
GetDateTimeAt(byte[] Buffer, int Pos)346         public static DateTime GetDateTimeAt(byte[] Buffer, int Pos)
347         {
348             int Year, Month, Day, Hour, Min, Sec, MSec;
349 
350             Year = BCDtoByte(Buffer[Pos]);
351             if (Year < 90)
352                 Year += 2000;
353             else
354                 Year += 1900;
355 
356             Month = BCDtoByte(Buffer[Pos + 1]);
357             Day = BCDtoByte(Buffer[Pos + 2]);
358             Hour = BCDtoByte(Buffer[Pos + 3]);
359             Min = BCDtoByte(Buffer[Pos + 4]);
360             Sec = BCDtoByte(Buffer[Pos + 5]);
361             MSec = (BCDtoByte(Buffer[Pos + 6]) * 10) + (BCDtoByte(Buffer[Pos + 7]) / 10);
362             try
363             {
364                 return new DateTime(Year, Month, Day, Hour, Min, Sec, MSec);
365             }
366             catch (System.ArgumentOutOfRangeException)
367             {
368                 return new DateTime(0);
369             }
370         }
SetDateTimeAt(byte[] Buffer, int Pos, DateTime Value)371         public static void SetDateTimeAt(byte[] Buffer, int Pos, DateTime Value)
372         {
373             int Year = Value.Year;
374             int Month = Value.Month;
375             int Day = Value.Day;
376             int Hour = Value.Hour;
377             int Min = Value.Minute;
378             int Sec = Value.Second;
379             int Dow = (int)Value.DayOfWeek + 1;
380             // MSecH = First two digits of miliseconds
381             int MsecH = Value.Millisecond / 10;
382             // MSecL = Last digit of miliseconds
383             int MsecL = Value.Millisecond % 10;
384             if (Year > 1999)
385                 Year -= 2000;
386 
387             Buffer[Pos] = ByteToBCD(Year);
388             Buffer[Pos + 1] = ByteToBCD(Month);
389             Buffer[Pos + 2] = ByteToBCD(Day);
390             Buffer[Pos + 3] = ByteToBCD(Hour);
391             Buffer[Pos + 4] = ByteToBCD(Min);
392             Buffer[Pos + 5] = ByteToBCD(Sec);
393             Buffer[Pos + 6] = ByteToBCD(MsecH);
394             Buffer[Pos + 7] = ByteToBCD(MsecL * 10 + Dow);
395         }
396         #endregion
397 
398         #region Get/Set DATE (S7 DATE)
GetDateAt(byte[] Buffer, int Pos)399         public static DateTime GetDateAt(byte[] Buffer, int Pos)
400         {
401             try
402             {
403                 return new DateTime(1990, 1, 1).AddDays(GetIntAt(Buffer, Pos));
404             }
405             catch (System.ArgumentOutOfRangeException)
406             {
407                 return new DateTime(0);
408             }
409         }
SetDateAt(byte[] Buffer, int Pos, DateTime Value)410         public static void SetDateAt(byte[] Buffer, int Pos, DateTime Value)
411         {
412             SetIntAt(Buffer, Pos, (Int16)(Value - new DateTime(1990, 1, 1)).Days);
413         }
414 
415         #endregion
416 
417         #region Get/Set TOD (S7 TIME_OF_DAY)
GetTODAt(byte[] Buffer, int Pos)418         public static DateTime GetTODAt(byte[] Buffer, int Pos)
419         {
420             try
421             {
422                 return new DateTime(0).AddMilliseconds(S7.GetDIntAt(Buffer, Pos));
423             }
424             catch (System.ArgumentOutOfRangeException)
425             {
426                 return new DateTime(0);
427             }
428         }
SetTODAt(byte[] Buffer, int Pos, DateTime Value)429         public static void SetTODAt(byte[] Buffer, int Pos, DateTime Value)
430         {
431             TimeSpan Time = Value.TimeOfDay;
432             SetDIntAt(Buffer, Pos, (Int32)Math.Round(Time.TotalMilliseconds));
433         }
434         #endregion
435 
436         #region Get/Set LTOD (S7 1500 LONG TIME_OF_DAY)
GetLTODAt(byte[] Buffer, int Pos)437         public static DateTime GetLTODAt(byte[] Buffer, int Pos)
438         {
439             // .NET Tick = 100 ns, S71500 Tick = 1 ns
440             try
441             {
442                 return new DateTime(Math.Abs(GetLIntAt(Buffer,Pos)/100));
443             }
444             catch (System.ArgumentOutOfRangeException)
445             {
446                 return new DateTime(0);
447             }
448         }
SetLTODAt(byte[] Buffer, int Pos, DateTime Value)449         public static void SetLTODAt(byte[] Buffer, int Pos, DateTime Value)
450         {
451             TimeSpan Time = Value.TimeOfDay;
452             SetLIntAt(Buffer, Pos, (Int64)Time.Ticks * 100);
453         }
454 
455         #endregion
456 
457         #region GET/SET LDT (S7 1500 Long Date and Time)
GetLDTAt(byte[] Buffer, int Pos)458         public static DateTime GetLDTAt(byte[] Buffer, int Pos)
459         {
460             try
461             {
462                 return new DateTime((GetLIntAt(Buffer, Pos) / 100) + bias);
463             }
464             catch (System.ArgumentOutOfRangeException)
465             {
466                 return new DateTime(0);
467             }
468         }
SetLDTAt(byte[] Buffer, int Pos, DateTime Value)469         public static void SetLDTAt(byte[] Buffer, int Pos, DateTime Value)
470         {
471             SetLIntAt(Buffer, Pos, (Value.Ticks-bias) * 100);
472         }
473         #endregion
474 
475         #region Get/Set DTL (S71200/1500 Date and Time)
476         // Thanks to Johan Cardoen for GetDTLAt
GetDTLAt(byte[] Buffer, int Pos)477         public static DateTime GetDTLAt(byte[] Buffer, int Pos)
478         {
479             int Year, Month, Day, Hour, Min, Sec, MSec;
480 
481             Year = Buffer[Pos] * 256 + Buffer[Pos + 1];
482             Month = Buffer[Pos + 2];
483             Day = Buffer[Pos + 3];
484             Hour = Buffer[Pos + 5];
485             Min = Buffer[Pos + 6];
486             Sec = Buffer[Pos + 7];
487             MSec = (int)GetUDIntAt(Buffer, Pos + 8)/1000000;
488 
489             try
490             {
491                 return new DateTime(Year, Month, Day, Hour, Min, Sec, MSec);
492             }
493             catch (System.ArgumentOutOfRangeException)
494             {
495                 return new DateTime(0);
496             }
497         }
SetDTLAt(byte[] Buffer, int Pos, DateTime Value)498         public static void SetDTLAt(byte[] Buffer, int Pos, DateTime Value)
499         {
500             short Year = (short)Value.Year;
501             byte Month = (byte)Value.Month;
502             byte Day = (byte)Value.Day;
503             byte Hour = (byte)Value.Hour;
504             byte Min = (byte)Value.Minute;
505             byte Sec = (byte)Value.Second;
506             byte Dow = (byte)(Value.DayOfWeek + 1);
507 
508             Int32 NanoSecs = Value.Millisecond * 1000000;
509 
510             var bytes_short = BitConverter.GetBytes(Year);
511 
512             Buffer[Pos] = bytes_short[1];
513             Buffer[Pos + 1] = bytes_short[0];
514             Buffer[Pos + 2] = Month;
515             Buffer[Pos + 3] = Day;
516             Buffer[Pos + 4] = Dow;
517             Buffer[Pos + 5] = Hour;
518             Buffer[Pos + 6] = Min;
519             Buffer[Pos + 7] = Sec;
520             SetDIntAt(Buffer, Pos + 8, NanoSecs);
521         }
522         #endregion
523 
524         #region Get/Set String (S7 String)
525         // Thanks to Pablo Agirre
GetStringAt(byte[] Buffer, int Pos)526         public static string GetStringAt(byte[] Buffer, int Pos)
527         {
528             int size = (int)Buffer[Pos + 1];
529             return Encoding.ASCII.GetString(Buffer, Pos + 2, size);
530         }
SetStringAt(byte[] Buffer, int Pos, int MaxLen, string Value)531         public static void SetStringAt(byte[] Buffer, int Pos, int MaxLen, string Value)
532         {
533             int size = Value.Length;
534             Buffer[Pos] = (byte)MaxLen;
535             Buffer[Pos + 1] = (byte)size;
536             Encoding.ASCII.GetBytes(Value, 0, size, Buffer, Pos + 2);
537         }
538         #endregion
539 
540         #region Get/Set Array of char (S7 ARRAY OF CHARS)
GetCharsAt(byte[] Buffer, int Pos, int Size)541         public static string GetCharsAt(byte[] Buffer, int Pos, int Size)
542         {
543             return Encoding.ASCII.GetString(Buffer, Pos , Size);
544         }
SetCharsAt(byte[] Buffer, int Pos, string Value)545         public static void SetCharsAt(byte[] Buffer, int Pos, string Value)
546         {
547             int MaxLen = Buffer.Length - Pos;
548             // Truncs the string if there's no room enough
549             if (MaxLen > Value.Length) MaxLen = Value.Length;
550             Encoding.ASCII.GetBytes(Value, 0, MaxLen, Buffer, Pos);
551         }
552         #endregion
553 
554         #endregion [Help Functions]
555     }
556 
557     public class S7MultiVar
558     {
559         #region [MultiRead/Write Helper]
560         private S7Client FClient;
561         private GCHandle[] Handles = new GCHandle[S7Client.MaxVars];
562         private int Count = 0;
563         private S7Client.S7DataItem[] Items = new S7Client.S7DataItem[S7Client.MaxVars];
564 
565         public int[] Results = new int[S7Client.MaxVars];
566 
S7MultiVar(S7Client Client)567         public S7MultiVar(S7Client Client)
568         {
569             FClient = Client;
570             for (int c = 0; c < S7Client.MaxVars; c++)
571                 Results[c] = (int)S7Client.errCliItemNotAvailable;
572         }
~S7MultiVar()573         ~S7MultiVar()
574         {
575             Clear();
576         }
577 
Add(Int32 Area, Int32 WordLen, Int32 DBNumber, Int32 Start, Int32 Amount, ref T[] Buffer)578         public bool Add<T>(Int32 Area, Int32 WordLen, Int32 DBNumber, Int32 Start, Int32 Amount, ref T[] Buffer)
579         {
580             return Add(Area, WordLen, DBNumber, Start, Amount, ref Buffer, 0);
581         }
582 
Add(Int32 Area, Int32 WordLen, Int32 DBNumber, Int32 Start, Int32 Amount, ref T[] Buffer, int Offset)583         public bool Add<T>(Int32 Area, Int32 WordLen, Int32 DBNumber, Int32 Start, Int32 Amount, ref T[] Buffer, int Offset)
584         {
585             if (Count < S7Client.MaxVars)
586             {
587                 Items[Count].Area = Area;
588                 Items[Count].WordLen = WordLen;
589                 Items[Count].Result = 0;
590                 Items[Count].DBNumber = DBNumber;
591                 Items[Count].Start = Start;
592                 Items[Count].Amount = Amount;
593                 GCHandle handle = GCHandle.Alloc(Buffer, GCHandleType.Pinned);
594                 if (IntPtr.Size == 4)
595                     Items[Count].pData = (IntPtr)(handle.AddrOfPinnedObject().ToInt32() + Offset * Marshal.SizeOf(typeof(T)));
596                 else
597                     Items[Count].pData = (IntPtr)(handle.AddrOfPinnedObject().ToInt64() + Offset * Marshal.SizeOf(typeof(T)));
598 
599                 Handles[Count] = handle;
600                 Count++;
601                 return true;
602             }
603             else
604                 return false;
605         }
606 
Read()607         public int Read()
608         {
609             int FunctionResult;
610             if (Count > 0)
611             {
612                 FunctionResult = FClient.ReadMultiVars(Items, Count);
613                 if (FunctionResult == 0)
614                     for (int c = 0; c < S7Client.MaxVars; c++)
615                         Results[c] = Items[c].Result;
616                 return FunctionResult;
617             }
618             else
619                 return (int)S7Client.errCliFunctionRefused;
620         }
Write()621         public int Write()
622         {
623             int FunctionResult;
624             if (Count > 0)
625             {
626                 FunctionResult = FClient.WriteMultiVars(Items, Count);
627                 if (FunctionResult == 0)
628                     for (int c = 0; c < S7Client.MaxVars; c++)
629                         Results[c] = Items[c].Result;
630                 return FunctionResult;
631             }
632             else
633                 return (int)S7Client.errCliFunctionRefused;
634         }
Clear()635         public void Clear()
636         {
637             for (int c = 0; c < Count; c++)
638             {
639                 if (Handles[c] != null)
640                     Handles[c].Free();
641             }
642             for (int c = 0; c < S7Client.MaxVars; c++)
643                 Results[c] = (int)S7Client.errCliItemNotAvailable;
644             Count = 0;
645         }
646         #endregion
647     }
648 
649     public class S7Client
650     {
651         #region [Constants, private vars and TypeDefs]
652         private const int MsgTextLen = 1024;
653         // Error codes
654         public static readonly uint errNegotiatingPDU            = 0x00100000;
655         public static readonly uint errCliInvalidParams          = 0x00200000;
656         public static readonly uint errCliJobPending             = 0x00300000;
657         public static readonly uint errCliTooManyItems           = 0x00400000;
658         public static readonly uint errCliInvalidWordLen         = 0x00500000;
659         public static readonly uint errCliPartialDataWritten     = 0x00600000;
660         public static readonly uint errCliSizeOverPDU            = 0x00700000;
661         public static readonly uint errCliInvalidPlcAnswer       = 0x00800000;
662         public static readonly uint errCliAddressOutOfRange      = 0x00900000;
663         public static readonly uint errCliInvalidTransportSize   = 0x00A00000;
664         public static readonly uint errCliWriteDataSizeMismatch  = 0x00B00000;
665         public static readonly uint errCliItemNotAvailable       = 0x00C00000;
666         public static readonly uint errCliInvalidValue           = 0x00D00000;
667         public static readonly uint errCliCannotStartPLC         = 0x00E00000;
668         public static readonly uint errCliAlreadyRun             = 0x00F00000;
669         public static readonly uint errCliCannotStopPLC          = 0x01000000;
670         public static readonly uint errCliCannotCopyRamToRom     = 0x01100000;
671         public static readonly uint errCliCannotCompress         = 0x01200000;
672         public static readonly uint errCliAlreadyStop            = 0x01300000;
673         public static readonly uint errCliFunNotAvailable        = 0x01400000;
674         public static readonly uint errCliUploadSequenceFailed   = 0x01500000;
675         public static readonly uint errCliInvalidDataSizeRecvd   = 0x01600000;
676         public static readonly uint errCliInvalidBlockType       = 0x01700000;
677         public static readonly uint errCliInvalidBlockNumber     = 0x01800000;
678         public static readonly uint errCliInvalidBlockSize       = 0x01900000;
679         public static readonly uint errCliDownloadSequenceFailed = 0x01A00000;
680         public static readonly uint errCliInsertRefused          = 0x01B00000;
681         public static readonly uint errCliDeleteRefused          = 0x01C00000;
682         public static readonly uint errCliNeedPassword           = 0x01D00000;
683         public static readonly uint errCliInvalidPassword        = 0x01E00000;
684         public static readonly uint errCliNoPasswordToSetOrClear = 0x01F00000;
685         public static readonly uint errCliJobTimeout             = 0x02000000;
686         public static readonly uint errCliPartialDataRead        = 0x02100000;
687         public static readonly uint errCliBufferTooSmall         = 0x02200000;
688         public static readonly uint errCliFunctionRefused        = 0x02300000;
689         public static readonly uint errCliDestroying             = 0x02400000;
690         public static readonly uint errCliInvalidParamNumber     = 0x02500000;
691         public static readonly uint errCliCannotChangeParam      = 0x02600000;
692 
693         // Area ID
694         public static readonly byte S7AreaPE = 0x81;
695         public static readonly byte S7AreaPA = 0x82;
696         public static readonly byte S7AreaMK = 0x83;
697         public static readonly byte S7AreaDB = 0x84;
698         public static readonly byte S7AreaCT = 0x1C;
699         public static readonly byte S7AreaTM = 0x1D;
700 
701         // Word Length
702         public static readonly int S7WLBit     = 0x01;
703         public static readonly int S7WLByte    = 0x02;
704         public static readonly int S7WLWord    = 0x04;
705         public static readonly int S7WLDWord   = 0x06;
706         public static readonly int S7WLReal    = 0x08;
707         public static readonly int S7WLCounter = 0x1C;
708         public static readonly int S7WLTimer   = 0x1D;
709 
710         // Block type
711         public static readonly byte Block_OB  = 0x38;
712         public static readonly byte Block_DB  = 0x41;
713         public static readonly byte Block_SDB = 0x42;
714         public static readonly byte Block_FC  = 0x43;
715         public static readonly byte Block_SFC = 0x44;
716         public static readonly byte Block_FB  = 0x45;
717         public static readonly byte Block_SFB = 0x46;
718 
719         // Sub Block Type
720         public static readonly byte SubBlk_OB  = 0x08;
721         public static readonly byte SubBlk_DB  = 0x0A;
722         public static readonly byte SubBlk_SDB = 0x0B;
723         public static readonly byte SubBlk_FC  = 0x0C;
724         public static readonly byte SubBlk_SFC = 0x0D;
725         public static readonly byte SubBlk_FB  = 0x0E;
726         public static readonly byte SubBlk_SFB = 0x0F;
727 
728         // Block languages
729         public static readonly byte BlockLangAWL   = 0x01;
730         public static readonly byte BlockLangKOP   = 0x02;
731         public static readonly byte BlockLangFUP   = 0x03;
732         public static readonly byte BlockLangSCL   = 0x04;
733         public static readonly byte BlockLangDB    = 0x05;
734         public static readonly byte BlockLangGRAPH = 0x06;
735 
736         // Max number of vars (multiread/write)
737         public static readonly int MaxVars = 20;
738 
739         // Client Connection Type
740         public static readonly UInt16 CONNTYPE_PG    = 0x01;  // Connect to the PLC as a PG
741         public static readonly UInt16 CONNTYPE_OP    = 0x02;  // Connect to the PLC as an OP
742         public static readonly UInt16 CONNTYPE_BASIC = 0x03;  // Basic connection
743 
744         // Job
745         private const int JobComplete = 0;
746         private const int JobPending = 1;
747 
748         private IntPtr Client;
749 
750         // New Data Item, Thanks to LanceL
751         [StructLayout(LayoutKind.Sequential, Pack = 1)]
752         public struct S7DataItem
753         {
754             public Int32 Area;
755             public Int32 WordLen;
756             public Int32 Result;
757             public Int32 DBNumber;
758             public Int32 Start;
759             public Int32 Amount;
760             public IntPtr pData;
761         }
762 
763         // Block List
764         [StructLayout(LayoutKind.Sequential, Pack = 1)] // <- "maybe" we don't need
765         public struct S7BlocksList
766         {
767             public Int32 OBCount;
768             public Int32 FBCount;
769             public Int32 FCCount;
770             public Int32 SFBCount;
771             public Int32 SFCCount;
772             public Int32 DBCount;
773             public Int32 SDBCount;
774         };
775 
776         // Packed Block Info
777         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
778         protected struct US7BlockInfo
779         {
780             public Int32 BlkType;
781             public Int32 BlkNumber;
782             public Int32 BlkLang;
783             public Int32 BlkFlags;
784             public Int32 MC7Size;  // The real size in bytes
785             public Int32 LoadSize;
786             public Int32 LocalData;
787             public Int32 SBBLength;
788             public Int32 CheckSum;
789             public Int32 Version;
790             // Chars info
791             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 11)]
792             public char[] CodeDate;
793             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 11)]
794             public char[] IntfDate;
795             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
796             public char[] Author;
797             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
798             public char[] Family;
799             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
800             public char[] Header;
801         };
802         private US7BlockInfo UBlockInfo;
803 
804         // Managed Block Info
805         public struct S7BlockInfo
806         {
807             public int BlkType;
808             public int BlkNumber;
809             public int BlkLang;
810             public int BlkFlags;
811             public int MC7Size;  // The real size in bytes
812             public int LoadSize;
813             public int LocalData;
814             public int SBBLength;
815             public int CheckSum;
816             public int Version;
817             // Chars info
818             public string CodeDate;
819             public string IntfDate;
820             public string Author;
821             public string Family;
822             public string Header;
823         };
824 
825         public ushort[] TS7BlocksOfType;
826 
827         // Packed Order Code + Version
828         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
829         protected struct US7OrderCode
830         {
831             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 21)]
832             public char[] Code;
833             public byte V1;
834             public byte V2;
835             public byte V3;
836         };
837         private US7OrderCode UOrderCode;
838 
839         // Managed Order Code + Version
840         public struct S7OrderCode
841         {
842             public string Code;
843             public byte V1;
844             public byte V2;
845             public byte V3;
846         };
847 
848         // Packed CPU Info
849         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
850         protected struct US7CpuInfo
851         {
852             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 33)]
853             public char[] ModuleTypeName;
854             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)]
855             public char[] SerialNumber;
856             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)]
857             public char[] ASName;
858             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 27)]
859             public char[] Copyright;
860             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 25)]
861             public char[] ModuleName;
862         };
863         private US7CpuInfo UCpuInfo;
864 
865         // Managed CPU Info
866         public struct S7CpuInfo
867         {
868             public string ModuleTypeName;
869             public string SerialNumber;
870             public string ASName;
871             public string Copyright;
872             public string ModuleName;
873         }
874 
875         [StructLayout(LayoutKind.Sequential, Pack = 1)]
876         public struct S7CpInfo
877         {
878             public Int32 MaxPduLengt;
879             public Int32 MaxConnections;
880             public Int32 MaxMpiRate;
881             public Int32 MaxBusRate;
882         };
883 
884         // See §33.1 of "System Software for S7-300/400 System and Standard Functions"
885         // and see SFC51 description too
886         [StructLayout(LayoutKind.Sequential, Pack = 1)]
887         public struct SZL_HEADER
888         {
889             public UInt16 LENTHDR;
890             public UInt16 N_DR;
891         };
892 
893         [StructLayout(LayoutKind.Sequential, Pack = 1)]
894         public struct S7SZL
895         {
896             public SZL_HEADER Header;
897             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x4000 - 4)]
898             public byte[] Data;
899         };
900 
901         // SZL List of available SZL IDs : same as SZL but List items are big-endian adjusted
902         [StructLayout(LayoutKind.Sequential, Pack = 1)]
903         public struct S7SZLList
904         {
905             public SZL_HEADER Header;
906             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x2000 - 2)]
907             public UInt16[] Data;
908         };
909 
910         // S7 Protection
911         // See §33.19 of "System Software for S7-300/400 System and Standard Functions"
912         [StructLayout(LayoutKind.Sequential, Pack = 1)]
913         public struct S7Protection  // Packed S7Protection
914         {
915             public UInt16 sch_schal;
916             public UInt16 sch_par;
917             public UInt16 sch_rel;
918             public UInt16 bart_sch;
919             public UInt16 anl_sch;
920         };
921 
922         // C++ time struct, functions to convert it from/to DateTime are provided ;-)
923         [StructLayout(LayoutKind.Sequential, Pack = 1)]
924         protected struct cpp_tm
925         {
926             public Int32 tm_sec;
927             public Int32 tm_min;
928             public Int32 tm_hour;
929             public Int32 tm_mday;
930             public Int32 tm_mon;
931             public Int32 tm_year;
932             public Int32 tm_wday;
933             public Int32 tm_yday;
934             public Int32 tm_isdst;
935         }
936         private cpp_tm tm;
937 
938         #endregion
939 
940         #region [Class Control]
941 
942         [DllImport(S7Consts.Snap7LibName)]
Cli_Create()943         protected static extern IntPtr Cli_Create();
S7Client()944         public S7Client()
945         {
946             Client = Cli_Create();
947         }
948 
949         [DllImport(S7Consts.Snap7LibName)]
Cli_Destroy(ref IntPtr Client)950         protected static extern int Cli_Destroy(ref IntPtr Client);
~S7Client()951         ~S7Client()
952         {
953             Cli_Destroy(ref Client);
954         }
955 
956         [DllImport(S7Consts.Snap7LibName)]
Cli_Connect(IntPtr Client)957         protected static extern int Cli_Connect(IntPtr Client);
Connect()958         public int Connect()
959         {
960             return Cli_Connect(Client);
961         }
962 
963         [DllImport(S7Consts.Snap7LibName)]
Cli_ConnectTo(IntPtr Client, [MarshalAs(UnmanagedType.LPStr)] string Address, int Rack, int Slot )964         protected static extern int Cli_ConnectTo(IntPtr Client,
965             [MarshalAs(UnmanagedType.LPStr)] string Address,
966             int Rack,
967             int Slot
968             );
969 
ConnectTo(string Address, int Rack, int Slot)970         public int ConnectTo(string Address, int Rack, int Slot)
971         {
972             return Cli_ConnectTo(Client, Address, Rack, Slot);
973         }
974 
975         [DllImport(S7Consts.Snap7LibName)]
Cli_SetConnectionParams(IntPtr Client, [MarshalAs(UnmanagedType.LPStr)] string Address, UInt16 LocalTSAP, UInt16 RemoteTSAP )976         protected static extern int Cli_SetConnectionParams(IntPtr Client,
977             [MarshalAs(UnmanagedType.LPStr)] string Address,
978             UInt16 LocalTSAP,
979             UInt16 RemoteTSAP
980             );
981 
SetConnectionParams(string Address, UInt16 LocalTSAP, UInt16 RemoteTSAP)982         public int SetConnectionParams(string Address, UInt16 LocalTSAP, UInt16 RemoteTSAP)
983         {
984             return Cli_SetConnectionParams(Client, Address, LocalTSAP, RemoteTSAP);
985         }
986 
987         [DllImport(S7Consts.Snap7LibName)]
Cli_SetConnectionType(IntPtr Client, UInt16 ConnectionType)988         protected static extern int Cli_SetConnectionType(IntPtr Client, UInt16 ConnectionType);
SetConnectionType(UInt16 ConnectionType)989         public int SetConnectionType(UInt16 ConnectionType)
990         {
991             return Cli_SetConnectionType(Client, ConnectionType);
992         }
993 
994         [DllImport(S7Consts.Snap7LibName)]
Cli_Disconnect(IntPtr Client)995         protected static extern int Cli_Disconnect(IntPtr Client);
Disconnect()996         public int Disconnect()
997         {
998             return Cli_Disconnect(Client);
999         }
1000 
1001         // Get/SetParam needs a void* parameter, internally it decides the kind of pointer
1002         // in accord to ParamNumber.
1003         // To avoid the use of unsafe code we split the DLL functions and use overloaded methods.
1004 
1005         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_GetParam")]
Cli_GetParam_i16(IntPtr Client, Int32 ParamNumber, ref Int16 IntValue)1006         protected static extern int Cli_GetParam_i16(IntPtr Client, Int32 ParamNumber, ref Int16 IntValue);
GetParam(Int32 ParamNumber, ref Int16 IntValue)1007         public int GetParam(Int32 ParamNumber, ref Int16 IntValue)
1008         {
1009             return Cli_GetParam_i16(Client, ParamNumber, ref IntValue);
1010         }
1011 
1012         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_GetParam")]
Cli_GetParam_u16(IntPtr Client, Int32 ParamNumber, ref UInt16 IntValue)1013         protected static extern int Cli_GetParam_u16(IntPtr Client, Int32 ParamNumber, ref UInt16 IntValue);
GetParam(Int32 ParamNumber, ref UInt16 IntValue)1014         public int GetParam(Int32 ParamNumber, ref UInt16 IntValue)
1015         {
1016             return Cli_GetParam_u16(Client, ParamNumber, ref IntValue);
1017         }
1018 
1019         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_GetParam")]
Cli_GetParam_i32(IntPtr Client, Int32 ParamNumber, ref Int32 IntValue)1020         protected static extern int Cli_GetParam_i32(IntPtr Client, Int32 ParamNumber, ref Int32 IntValue);
GetParam(Int32 ParamNumber, ref Int32 IntValue)1021         public int GetParam(Int32 ParamNumber, ref Int32 IntValue)
1022         {
1023             return Cli_GetParam_i32(Client, ParamNumber, ref IntValue);
1024         }
1025 
1026         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_GetParam")]
Cli_GetParam_u32(IntPtr Client, Int32 ParamNumber, ref UInt32 IntValue)1027         protected static extern int Cli_GetParam_u32(IntPtr Client, Int32 ParamNumber, ref UInt32 IntValue);
GetParam(Int32 ParamNumber, ref UInt32 IntValue)1028         public int GetParam(Int32 ParamNumber, ref UInt32 IntValue)
1029         {
1030             return Cli_GetParam_u32(Client, ParamNumber, ref IntValue);
1031         }
1032 
1033         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_GetParam")]
Cli_GetParam_i64(IntPtr Client, Int32 ParamNumber, ref Int64 IntValue)1034         protected static extern int Cli_GetParam_i64(IntPtr Client, Int32 ParamNumber, ref Int64 IntValue);
GetParam(Int32 ParamNumber, ref Int64 IntValue)1035         public int GetParam(Int32 ParamNumber, ref Int64 IntValue)
1036         {
1037             return Cli_GetParam_i64(Client, ParamNumber, ref IntValue);
1038         }
1039 
1040         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_GetParam")]
Cli_GetParam_u64(IntPtr Client, Int32 ParamNumber, ref UInt64 IntValue)1041         protected static extern int Cli_GetParam_u64(IntPtr Client, Int32 ParamNumber, ref UInt64 IntValue);
GetParam(Int32 ParamNumber, ref UInt64 IntValue)1042         public int GetParam(Int32 ParamNumber, ref UInt64 IntValue)
1043         {
1044             return Cli_GetParam_u64(Client, ParamNumber, ref IntValue);
1045         }
1046 
1047         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_SetParam")]
Cli_SetParam_i16(IntPtr Client, Int32 ParamNumber, ref Int16 IntValue)1048         protected static extern int Cli_SetParam_i16(IntPtr Client, Int32 ParamNumber, ref Int16 IntValue);
SetParam(Int32 ParamNumber, ref Int16 IntValue)1049         public int SetParam(Int32 ParamNumber, ref Int16 IntValue)
1050         {
1051             return Cli_SetParam_i16(Client, ParamNumber, ref IntValue);
1052         }
1053 
1054         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_SetParam")]
Cli_SetParam_u16(IntPtr Client, Int32 ParamNumber, ref UInt16 IntValue)1055         protected static extern int Cli_SetParam_u16(IntPtr Client, Int32 ParamNumber, ref UInt16 IntValue);
SetParam(Int32 ParamNumber, ref UInt16 IntValue)1056         public int SetParam(Int32 ParamNumber, ref UInt16 IntValue)
1057         {
1058             return Cli_SetParam_u16(Client, ParamNumber, ref IntValue);
1059         }
1060 
1061         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_SetParam")]
Cli_SetParam_i32(IntPtr Client, Int32 ParamNumber, ref Int32 IntValue)1062         protected static extern int Cli_SetParam_i32(IntPtr Client, Int32 ParamNumber, ref Int32 IntValue);
SetParam(Int32 ParamNumber, ref Int32 IntValue)1063         public int SetParam(Int32 ParamNumber, ref Int32 IntValue)
1064         {
1065             return Cli_SetParam_i32(Client, ParamNumber, ref IntValue);
1066         }
1067 
1068         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_SetParam")]
Cli_SetParam_u32(IntPtr Client, Int32 ParamNumber, ref UInt32 IntValue)1069         protected static extern int Cli_SetParam_u32(IntPtr Client, Int32 ParamNumber, ref UInt32 IntValue);
SetParam(Int32 ParamNumber, ref UInt32 IntValue)1070         public int SetParam(Int32 ParamNumber, ref UInt32 IntValue)
1071         {
1072             return Cli_SetParam_u32(Client, ParamNumber, ref IntValue);
1073         }
1074 
1075         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_SetParam")]
Cli_SetParam_i64(IntPtr Client, Int32 ParamNumber, ref Int64 IntValue)1076         protected static extern int Cli_SetParam_i64(IntPtr Client, Int32 ParamNumber, ref Int64 IntValue);
SetParam(Int32 ParamNumber, ref Int64 IntValue)1077         public int SetParam(Int32 ParamNumber, ref Int64 IntValue)
1078         {
1079             return Cli_SetParam_i64(Client, ParamNumber, ref IntValue);
1080         }
1081 
1082         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_SetParam")]
Cli_SetParam_u64(IntPtr Client, Int32 ParamNumber, ref UInt64 IntValue)1083         protected static extern int Cli_SetParam_u64(IntPtr Client, Int32 ParamNumber, ref UInt64 IntValue);
SetParam(Int32 ParamNumber, ref UInt64 IntValue)1084         public int SetParam(Int32 ParamNumber, ref UInt64 IntValue)
1085         {
1086             return Cli_SetParam_u64(Client, ParamNumber, ref IntValue);
1087         }
1088 
S7CliCompletion(IntPtr usrPtr, int opCode, int opResult)1089         public delegate void S7CliCompletion(IntPtr usrPtr, int opCode, int opResult);
1090 
1091         [DllImport(S7Consts.Snap7LibName)]
Cli_SetAsCallback(IntPtr Client, S7CliCompletion Completion, IntPtr usrPtr)1092         protected static extern int Cli_SetAsCallback(IntPtr Client, S7CliCompletion Completion, IntPtr usrPtr);
SetAsCallBack(S7CliCompletion Completion, IntPtr usrPtr)1093         public int SetAsCallBack(S7CliCompletion Completion, IntPtr usrPtr)
1094         {
1095             return Cli_SetAsCallback(Client, Completion, usrPtr);
1096         }
1097 
1098         #endregion
1099 
1100         #region [Data I/O main functions]
1101 
1102         [DllImport(S7Consts.Snap7LibName)]
Cli_ReadArea(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)1103         protected static extern int Cli_ReadArea(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer);
ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)1104         public int ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)
1105         {
1106             return Cli_ReadArea(Client, Area, DBNumber, Start, Amount, WordLen, Buffer);
1107         }
1108 
1109         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Cli_ReadArea")]
Cli_ReadArea_ptr(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, IntPtr Pointer)1110         protected static extern int Cli_ReadArea_ptr(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, IntPtr Pointer);
ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, IntPtr Pointer)1111         public int ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, IntPtr Pointer)
1112         {
1113             return Cli_ReadArea_ptr(Client, Area, DBNumber, Start, Amount, WordLen, Pointer);
1114         }
1115 
1116         [DllImport(S7Consts.Snap7LibName)]
Cli_WriteArea(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)1117         protected static extern int Cli_WriteArea(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer);
WriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)1118         public int WriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)
1119         {
1120             return Cli_WriteArea(Client, Area, DBNumber, Start, Amount, WordLen, Buffer);
1121         }
1122 
1123         [DllImport(S7Consts.Snap7LibName)]
Cli_ReadMultiVars(IntPtr Client, ref S7DataItem Item, int ItemsCount)1124         protected static extern int Cli_ReadMultiVars(IntPtr Client, ref S7DataItem Item, int ItemsCount);
ReadMultiVars(S7DataItem[] Items, int ItemsCount)1125         public int ReadMultiVars(S7DataItem[] Items, int ItemsCount)
1126         {
1127             return Cli_ReadMultiVars(Client, ref Items[0], ItemsCount);
1128         }
1129 
1130         [DllImport(S7Consts.Snap7LibName)]
Cli_WriteMultiVars(IntPtr Client, ref S7DataItem Item, int ItemsCount)1131         protected static extern int Cli_WriteMultiVars(IntPtr Client, ref S7DataItem Item, int ItemsCount);
WriteMultiVars(S7DataItem[] Items, int ItemsCount)1132         public int WriteMultiVars(S7DataItem[] Items, int ItemsCount)
1133         {
1134             return Cli_WriteMultiVars(Client, ref Items[0], ItemsCount);
1135         }
1136 
1137         #endregion
1138 
1139         #region [Data I/O lean functions]
1140 
1141         [DllImport(S7Consts.Snap7LibName)]
Cli_DBRead(IntPtr Client, int DBNumber, int Start, int Size, byte[] Buffer)1142         protected static extern int Cli_DBRead(IntPtr Client, int DBNumber, int Start, int Size, byte[] Buffer);
DBRead(int DBNumber, int Start, int Size, byte[] Buffer)1143         public int DBRead(int DBNumber, int Start, int Size, byte[] Buffer)
1144         {
1145             return Cli_DBRead(Client, DBNumber, Start, Size, Buffer);
1146         }
1147 
1148         [DllImport(S7Consts.Snap7LibName)]
Cli_DBWrite(IntPtr Client, int DBNumber, int Start, int Size, byte[] Buffer)1149         protected static extern int Cli_DBWrite(IntPtr Client, int DBNumber, int Start, int Size, byte[] Buffer);
DBWrite(int DBNumber, int Start, int Size, byte[] Buffer)1150         public int DBWrite(int DBNumber, int Start, int Size, byte[] Buffer)
1151         {
1152             return Cli_DBWrite(Client, DBNumber, Start, Size, Buffer);
1153         }
1154 
1155         [DllImport(S7Consts.Snap7LibName)]
Cli_MBRead(IntPtr Client, int Start, int Size, byte[] Buffer)1156         protected static extern int Cli_MBRead(IntPtr Client, int Start, int Size, byte[] Buffer);
MBRead(int Start, int Size, byte[] Buffer)1157         public int MBRead(int Start, int Size, byte[] Buffer)
1158         {
1159             return Cli_MBRead(Client, Start, Size, Buffer);
1160         }
1161 
1162         [DllImport(S7Consts.Snap7LibName)]
Cli_MBWrite(IntPtr Client, int Start, int Size, byte[] Buffer)1163         protected static extern int Cli_MBWrite(IntPtr Client, int Start, int Size, byte[] Buffer);
MBWrite(int Start, int Size, byte[] Buffer)1164         public int MBWrite(int Start, int Size, byte[] Buffer)
1165         {
1166             return Cli_MBWrite(Client, Start, Size, Buffer);
1167         }
1168 
1169         [DllImport(S7Consts.Snap7LibName)]
Cli_EBRead(IntPtr Client, int Start, int Size, byte[] Buffer)1170         protected static extern int Cli_EBRead(IntPtr Client, int Start, int Size, byte[] Buffer);
EBRead(int Start, int Size, byte[] Buffer)1171         public int EBRead(int Start, int Size, byte[] Buffer)
1172         {
1173             return Cli_EBRead(Client, Start, Size, Buffer);
1174         }
1175 
1176         [DllImport(S7Consts.Snap7LibName)]
Cli_EBWrite(IntPtr Client, int Start, int Size, byte[] Buffer)1177         protected static extern int Cli_EBWrite(IntPtr Client, int Start, int Size, byte[] Buffer);
EBWrite(int Start, int Size, byte[] Buffer)1178         public int EBWrite(int Start, int Size, byte[] Buffer)
1179         {
1180             return Cli_EBWrite(Client, Start, Size, Buffer);
1181         }
1182 
1183         [DllImport(S7Consts.Snap7LibName)]
Cli_ABRead(IntPtr Client, int Start, int Size, byte[] Buffer)1184         protected static extern int Cli_ABRead(IntPtr Client, int Start, int Size, byte[] Buffer);
ABRead(int Start, int Size, byte[] Buffer)1185         public int ABRead(int Start, int Size, byte[] Buffer)
1186         {
1187             return Cli_ABRead(Client, Start, Size, Buffer);
1188         }
1189 
1190         [DllImport(S7Consts.Snap7LibName)]
Cli_ABWrite(IntPtr Client, int Start, int Size, byte[] Buffer)1191         protected static extern int Cli_ABWrite(IntPtr Client, int Start, int Size, byte[] Buffer);
ABWrite(int Start, int Size, byte[] Buffer)1192         public int ABWrite(int Start, int Size, byte[] Buffer)
1193         {
1194             return Cli_ABWrite(Client, Start, Size, Buffer);
1195         }
1196 
1197         [DllImport(S7Consts.Snap7LibName)]
Cli_TMRead(IntPtr Client, int Start, int Amount, ushort[] Buffer)1198         protected static extern int Cli_TMRead(IntPtr Client, int Start, int Amount, ushort[] Buffer);
TMRead(int Start, int Amount, ushort[] Buffer)1199         public int TMRead(int Start, int Amount, ushort[] Buffer)
1200         {
1201             return Cli_TMRead(Client, Start, Amount, Buffer);
1202         }
1203 
1204         [DllImport(S7Consts.Snap7LibName)]
Cli_TMWrite(IntPtr Client, int Start, int Amount, ushort[] Buffer)1205         protected static extern int Cli_TMWrite(IntPtr Client, int Start, int Amount, ushort[] Buffer);
TMWrite(int Start, int Amount, ushort[] Buffer)1206         public int TMWrite(int Start, int Amount, ushort[] Buffer)
1207         {
1208             return Cli_TMWrite(Client, Start, Amount, Buffer);
1209         }
1210 
1211         [DllImport(S7Consts.Snap7LibName)]
Cli_CTRead(IntPtr Client, int Start, int Amount, ushort[] Buffer)1212         protected static extern int Cli_CTRead(IntPtr Client, int Start, int Amount, ushort[] Buffer);
CTRead(int Start, int Amount, ushort[] Buffer)1213         public int CTRead(int Start, int Amount, ushort[] Buffer)
1214         {
1215             return Cli_CTRead(Client, Start, Amount, Buffer);
1216         }
1217 
1218         [DllImport(S7Consts.Snap7LibName)]
Cli_CTWrite(IntPtr Client, int Start, int Amount, ushort[] Buffer)1219         protected static extern int Cli_CTWrite(IntPtr Client, int Start, int Amount, ushort[] Buffer);
CTWrite(int Start, int Amount, ushort[] Buffer)1220         public int CTWrite(int Start, int Amount, ushort[] Buffer)
1221         {
1222             return Cli_CTWrite(Client, Start, Amount, Buffer);
1223         }
1224 
1225         #endregion
1226 
1227         #region [Directory functions]
1228 
1229         [DllImport(S7Consts.Snap7LibName)]
Cli_ListBlocks(IntPtr Client, ref S7BlocksList List)1230         protected static extern int Cli_ListBlocks(IntPtr Client, ref S7BlocksList List);
ListBlocks(ref S7BlocksList List)1231         public int ListBlocks(ref S7BlocksList List)
1232         {
1233             return Cli_ListBlocks(Client, ref List);
1234         }
1235 
1236         [DllImport(S7Consts.Snap7LibName)]
Cli_GetAgBlockInfo(IntPtr Client, int BlockType, int BlockNum, ref US7BlockInfo Info)1237         protected static extern int Cli_GetAgBlockInfo(IntPtr Client, int BlockType, int BlockNum, ref US7BlockInfo Info);
GetAgBlockInfo(int BlockType, int BlockNum, ref S7BlockInfo Info)1238         public int GetAgBlockInfo(int BlockType, int BlockNum, ref S7BlockInfo Info)
1239         {
1240             int res = Cli_GetAgBlockInfo(Client, BlockType, BlockNum, ref UBlockInfo);
1241             // Packed->Managed
1242             if (res == 0)
1243             {
1244                 Info.BlkType = UBlockInfo.BlkType;
1245                 Info.BlkNumber = UBlockInfo.BlkNumber;
1246                 Info.BlkLang = UBlockInfo.BlkLang;
1247                 Info.BlkFlags = UBlockInfo.BlkFlags;
1248                 Info.MC7Size = UBlockInfo.MC7Size;
1249                 Info.LoadSize = UBlockInfo.LoadSize;
1250                 Info.LocalData = UBlockInfo.LocalData;
1251                 Info.SBBLength = UBlockInfo.SBBLength;
1252                 Info.CheckSum = UBlockInfo.CheckSum;
1253                 Info.Version = UBlockInfo.Version;
1254                 // Chars info
1255                 Info.CodeDate = new string(UBlockInfo.CodeDate);
1256                 Info.IntfDate = new string(UBlockInfo.IntfDate);
1257                 Info.Author = new string(UBlockInfo.Author);
1258                 Info.Family = new string(UBlockInfo.Family);
1259                 Info.Header = new string(UBlockInfo.Header);
1260             }
1261             return res;
1262         }
1263 
1264         [DllImport(S7Consts.Snap7LibName)]
Cli_GetPgBlockInfo(IntPtr Client, ref US7BlockInfo Info, byte[] Buffer, Int32 Size)1265         protected static extern int Cli_GetPgBlockInfo(IntPtr Client, ref US7BlockInfo Info, byte[] Buffer, Int32 Size);
GetPgBlockInfo(ref S7BlockInfo Info, byte[] Buffer, int Size)1266         public int GetPgBlockInfo(ref S7BlockInfo Info, byte[] Buffer, int Size)
1267         {
1268             int res = Cli_GetPgBlockInfo(Client, ref UBlockInfo, Buffer, Size);
1269             // Packed->Managed
1270             if (res == 0)
1271             {
1272                 Info.BlkType = UBlockInfo.BlkType;
1273                 Info.BlkNumber = UBlockInfo.BlkNumber;
1274                 Info.BlkLang = UBlockInfo.BlkLang;
1275                 Info.BlkFlags = UBlockInfo.BlkFlags;
1276                 Info.MC7Size = UBlockInfo.MC7Size;
1277                 Info.LoadSize = UBlockInfo.LoadSize;
1278                 Info.LocalData = UBlockInfo.LocalData;
1279                 Info.SBBLength = UBlockInfo.SBBLength;
1280                 Info.CheckSum = UBlockInfo.CheckSum;
1281                 Info.Version = UBlockInfo.Version;
1282                 // Chars info
1283                 Info.CodeDate = new string(UBlockInfo.CodeDate);
1284                 Info.IntfDate = new string(UBlockInfo.IntfDate);
1285                 Info.Author = new string(UBlockInfo.Author);
1286                 Info.Family = new string(UBlockInfo.Family);
1287                 Info.Header = new string(UBlockInfo.Header);
1288             }
1289             return res;
1290         }
1291 
1292         [DllImport(S7Consts.Snap7LibName)]
Cli_ListBlocksOfType(IntPtr Client, Int32 BlockType, ushort[] List, ref int ItemsCount)1293         protected static extern int Cli_ListBlocksOfType(IntPtr Client, Int32 BlockType, ushort[] List, ref int ItemsCount);
ListBlocksOfType(int BlockType, ushort[] List, ref int ItemsCount)1294         public int ListBlocksOfType(int BlockType, ushort[] List, ref int ItemsCount)
1295         {
1296             return Cli_ListBlocksOfType(Client, BlockType, List, ref ItemsCount);
1297         }
1298 
1299         #endregion
1300 
1301         #region [Blocks functions]
1302 
1303         [DllImport(S7Consts.Snap7LibName)]
Cli_Upload(IntPtr Client, int BlockType, int BlockNum, byte[] UsrData, ref int Size)1304         protected static extern int Cli_Upload(IntPtr Client, int BlockType, int BlockNum, byte[] UsrData, ref int Size);
Upload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)1305         public int Upload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)
1306         {
1307             return Cli_Upload(Client, BlockType, BlockNum, UsrData, ref Size);
1308         }
1309 
1310         [DllImport(S7Consts.Snap7LibName)]
Cli_FullUpload(IntPtr Client, int BlockType, int BlockNum, byte[] UsrData, ref int Size)1311         protected static extern int Cli_FullUpload(IntPtr Client, int BlockType, int BlockNum, byte[] UsrData, ref int Size);
FullUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)1312         public int FullUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)
1313         {
1314             return Cli_FullUpload(Client, BlockType, BlockNum, UsrData, ref Size);
1315         }
1316 
1317         [DllImport(S7Consts.Snap7LibName)]
Cli_Download(IntPtr Client, int BlockNum, byte[] UsrData, int Size)1318         protected static extern int Cli_Download(IntPtr Client, int BlockNum, byte[] UsrData, int Size);
Download(int BlockNum, byte[] UsrData, int Size)1319         public int Download(int BlockNum, byte[] UsrData, int Size)
1320         {
1321             return Cli_Download(Client, BlockNum, UsrData, Size);
1322         }
1323 
1324         [DllImport(S7Consts.Snap7LibName)]
Cli_Delete(IntPtr Client, int BlockType, int BlockNum)1325         protected static extern int Cli_Delete(IntPtr Client, int BlockType, int BlockNum);
Delete(int BlockType, int BlockNum)1326         public int Delete(int BlockType, int BlockNum)
1327         {
1328             return Cli_Delete(Client, BlockType, BlockNum);
1329         }
1330 
1331         [DllImport(S7Consts.Snap7LibName)]
Cli_DBGet(IntPtr Client, int DBNumber, byte[] UsrData, ref int Size)1332         protected static extern int Cli_DBGet(IntPtr Client, int DBNumber, byte[] UsrData, ref int Size);
DBGet(int DBNumber, byte[] UsrData, ref int Size)1333         public int DBGet(int DBNumber, byte[] UsrData, ref int Size)
1334         {
1335             return Cli_DBGet(Client, DBNumber, UsrData, ref Size);
1336         }
1337 
1338         [DllImport(S7Consts.Snap7LibName)]
Cli_DBFill(IntPtr Client, int DBNumber, int FillChar)1339         protected static extern int Cli_DBFill(IntPtr Client, int DBNumber, int FillChar);
DBFill(int DBNumber, int FillChar)1340         public int DBFill(int DBNumber, int FillChar)
1341         {
1342             return Cli_DBFill(Client, DBNumber, FillChar);
1343         }
1344 
1345         #endregion
1346 
1347         #region [Date/Time functions]
1348 
1349         [DllImport(S7Consts.Snap7LibName)]
Cli_GetPlcDateTime(IntPtr Client, ref cpp_tm tm)1350         protected static extern int Cli_GetPlcDateTime(IntPtr Client, ref cpp_tm tm);
GetPlcDateTime(ref DateTime DT)1351         public int GetPlcDateTime(ref DateTime DT)
1352         {
1353             int res = Cli_GetPlcDateTime(Client, ref tm);
1354             if (res == 0)
1355             {
1356                 // Packed->Managed
1357                 DateTime PlcDT = new DateTime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
1358                 DT = PlcDT;
1359             }
1360             return res;
1361         }
1362 
1363         [DllImport(S7Consts.Snap7LibName)]
Cli_SetPlcDateTime(IntPtr Client, ref cpp_tm tm)1364         protected static extern int Cli_SetPlcDateTime(IntPtr Client, ref cpp_tm tm);
SetPlcDateTime(DateTime DT)1365         public int SetPlcDateTime(DateTime DT)
1366         {
1367 
1368             // Managed->Packed
1369             tm.tm_year = DT.Year - 1900;
1370             tm.tm_mon = DT.Month-1;
1371             tm.tm_mday = DT.Day;
1372             tm.tm_hour = DT.Hour;
1373             tm.tm_min = DT.Minute;
1374             tm.tm_sec = DT.Second;
1375 
1376             return Cli_SetPlcDateTime(Client, ref tm);
1377         }
1378 
1379         [DllImport(S7Consts.Snap7LibName)]
Cli_SetPlcSystemDateTime(IntPtr Client)1380         protected static extern int Cli_SetPlcSystemDateTime(IntPtr Client);
SetPlcSystemDateTime()1381         public int SetPlcSystemDateTime()
1382         {
1383             return Cli_SetPlcSystemDateTime(Client);
1384         }
1385 
1386         #endregion
1387 
1388         #region [System Info functions]
1389 
1390         [DllImport(S7Consts.Snap7LibName)]
Cli_GetOrderCode(IntPtr Client, ref US7OrderCode Info)1391         protected static extern int Cli_GetOrderCode(IntPtr Client, ref US7OrderCode Info);
GetOrderCode(ref S7OrderCode Info)1392         public int GetOrderCode(ref S7OrderCode Info)
1393         {
1394             int res = Cli_GetOrderCode(Client, ref UOrderCode);
1395             // Packed->Managed
1396             if (res == 0)
1397             {
1398                 Info.Code = new string(UOrderCode.Code);
1399                 Info.V1 = UOrderCode.V1;
1400                 Info.V2 = UOrderCode.V2;
1401                 Info.V3 = UOrderCode.V3;
1402             }
1403             return res;
1404         }
1405 
1406         [DllImport(S7Consts.Snap7LibName)]
Cli_GetCpuInfo(IntPtr Client, ref US7CpuInfo Info)1407         protected static extern int Cli_GetCpuInfo(IntPtr Client, ref US7CpuInfo Info);
GetCpuInfo(ref S7CpuInfo Info)1408         public int GetCpuInfo(ref S7CpuInfo Info)
1409         {
1410             int res = Cli_GetCpuInfo(Client, ref UCpuInfo);
1411             // Packed->Managed
1412             if (res == 0)
1413             {
1414                 Info.ModuleTypeName = new string(UCpuInfo.ModuleTypeName);
1415                 Info.SerialNumber = new string(UCpuInfo.SerialNumber);
1416                 Info.ASName = new string(UCpuInfo.ASName);
1417                 Info.Copyright = new string(UCpuInfo.Copyright);
1418                 Info.ModuleName = new string(UCpuInfo.ModuleName);
1419             }
1420             return res;
1421         }
1422 
1423         [DllImport(S7Consts.Snap7LibName)]
Cli_GetCpInfo(IntPtr Client, ref S7CpInfo Info)1424         protected static extern int Cli_GetCpInfo(IntPtr Client, ref S7CpInfo Info);
1425 
GetCpInfo(ref S7CpInfo Info)1426         public int GetCpInfo(ref S7CpInfo Info)
1427         {
1428             return Cli_GetCpInfo(Client, ref Info);
1429         }
1430 
1431         [DllImport(S7Consts.Snap7LibName)]
Cli_ReadSZL(IntPtr Client, int ID, int Index, ref S7SZL Data, ref Int32 Size)1432         protected static extern int Cli_ReadSZL(IntPtr Client, int ID, int Index, ref S7SZL Data, ref Int32 Size);
ReadSZL(int ID, int Index, ref S7SZL Data, ref Int32 Size)1433         public int ReadSZL(int ID, int Index, ref S7SZL Data, ref Int32 Size)
1434         {
1435             return Cli_ReadSZL(Client, ID, Index, ref Data, ref Size);
1436         }
1437 
1438         [DllImport(S7Consts.Snap7LibName)]
Cli_ReadSZLList(IntPtr Client, ref S7SZLList List, ref Int32 ItemsCount)1439         protected static extern int Cli_ReadSZLList(IntPtr Client, ref S7SZLList List, ref Int32 ItemsCount);
ReadSZLList(ref S7SZLList List, ref Int32 ItemsCount)1440         public int ReadSZLList(ref S7SZLList List, ref Int32 ItemsCount)
1441         {
1442             return Cli_ReadSZLList(Client, ref List, ref ItemsCount);
1443         }
1444 
1445         #endregion
1446 
1447         #region [Control functions]
1448 
1449         [DllImport(S7Consts.Snap7LibName)]
Cli_PlcHotStart(IntPtr Client)1450         protected static extern int Cli_PlcHotStart(IntPtr Client);
PlcHotStart()1451         public int PlcHotStart()
1452         {
1453             return Cli_PlcHotStart(Client);
1454         }
1455 
1456         [DllImport(S7Consts.Snap7LibName)]
Cli_PlcColdStart(IntPtr Client)1457         protected static extern int Cli_PlcColdStart(IntPtr Client);
PlcColdStart()1458         public int PlcColdStart()
1459         {
1460             return Cli_PlcColdStart(Client);
1461         }
1462 
1463         [DllImport(S7Consts.Snap7LibName)]
Cli_PlcStop(IntPtr Client)1464         protected static extern int Cli_PlcStop(IntPtr Client);
PlcStop()1465         public int PlcStop()
1466         {
1467             return Cli_PlcStop(Client);
1468         }
1469 
1470         [DllImport(S7Consts.Snap7LibName)]
Cli_CopyRamToRom(IntPtr Client, UInt32 Timeout)1471         protected static extern int Cli_CopyRamToRom(IntPtr Client, UInt32 Timeout);
PlcCopyRamToRom(UInt32 Timeout)1472         public int PlcCopyRamToRom(UInt32 Timeout)
1473         {
1474             return Cli_CopyRamToRom(Client, Timeout);
1475         }
1476 
1477         [DllImport(S7Consts.Snap7LibName)]
Cli_Compress(IntPtr Client, UInt32 Timeout)1478         protected static extern int Cli_Compress(IntPtr Client, UInt32 Timeout);
PlcCompress(UInt32 Timeout)1479         public int PlcCompress(UInt32 Timeout)
1480         {
1481             return Cli_Compress(Client, Timeout);
1482         }
1483 
1484         [DllImport(S7Consts.Snap7LibName)]
Cli_GetPlcStatus(IntPtr Client, ref Int32 Status)1485         protected static extern int Cli_GetPlcStatus(IntPtr Client, ref Int32 Status);
PlcGetStatus(ref Int32 Status)1486         public int PlcGetStatus(ref Int32 Status)
1487         {
1488             return Cli_GetPlcStatus(Client, ref Status);
1489         }
1490 
1491         #endregion
1492 
1493         #region [Security functions]
1494 
1495         [DllImport(S7Consts.Snap7LibName)]
Cli_GetProtection(IntPtr Client, ref S7Protection Protection)1496         protected static extern int Cli_GetProtection(IntPtr Client, ref S7Protection Protection);
GetProtection(ref S7Protection Protection)1497         public int GetProtection(ref S7Protection Protection)
1498         {
1499             return Cli_GetProtection(Client, ref Protection);
1500         }
1501 
1502         [DllImport(S7Consts.Snap7LibName)]
Cli_SetSessionPassword(IntPtr Client, [MarshalAs(UnmanagedType.LPStr)] string Password)1503         protected static extern int Cli_SetSessionPassword(IntPtr Client, [MarshalAs(UnmanagedType.LPStr)] string Password);
SetSessionPassword(string Password)1504         public int SetSessionPassword(string Password)
1505         {
1506             return Cli_SetSessionPassword(Client, Password);
1507         }
1508 
1509         [DllImport(S7Consts.Snap7LibName)]
Cli_ClearSessionPassword(IntPtr Client)1510         protected static extern int Cli_ClearSessionPassword(IntPtr Client);
ClearSessionPassword()1511         public int ClearSessionPassword()
1512         {
1513             return Cli_ClearSessionPassword(Client);
1514         }
1515 
1516         #endregion
1517 
1518         #region [Low Level]
1519 
1520         [DllImport(S7Consts.Snap7LibName)]
Cli_IsoExchangeBuffer(IntPtr Client, byte[] Buffer, ref Int32 Size)1521         protected static extern int Cli_IsoExchangeBuffer(IntPtr Client, byte[] Buffer, ref Int32 Size);
IsoExchangeBuffer(byte[] Buffer, ref Int32 Size)1522         public int IsoExchangeBuffer(byte[] Buffer, ref Int32 Size)
1523         {
1524             return Cli_IsoExchangeBuffer(Client, Buffer, ref Size);
1525         }
1526 
1527         #endregion
1528 
1529         #region [Async functions]
1530 
1531         [DllImport(S7Consts.Snap7LibName)]
Cli_AsReadArea(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)1532         protected static extern int Cli_AsReadArea(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer);
AsReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)1533         public int AsReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)
1534         {
1535             return Cli_AsReadArea(Client, Area, DBNumber, Start, Amount, WordLen, Buffer);
1536         }
1537 
1538         [DllImport(S7Consts.Snap7LibName)]
Cli_AsWriteArea(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)1539         protected static extern int Cli_AsWriteArea(IntPtr Client, int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer);
AsWriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)1540         public int AsWriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)
1541         {
1542             return Cli_AsWriteArea(Client, Area, DBNumber, Start, Amount, WordLen, Buffer);
1543         }
1544 
1545         [DllImport(S7Consts.Snap7LibName)]
Cli_AsDBRead(IntPtr Client, int DBNumber, int Start, int Size, byte[] Buffer)1546         protected static extern int Cli_AsDBRead(IntPtr Client, int DBNumber, int Start, int Size, byte[] Buffer);
AsDBRead(int DBNumber, int Start, int Size, byte[] Buffer)1547         public int AsDBRead(int DBNumber, int Start, int Size, byte[] Buffer)
1548         {
1549             return Cli_AsDBRead(Client, DBNumber, Start, Size, Buffer);
1550         }
1551 
1552         [DllImport(S7Consts.Snap7LibName)]
Cli_AsDBWrite(IntPtr Client, int DBNumber, int Start, int Size, byte[] Buffer)1553         protected static extern int Cli_AsDBWrite(IntPtr Client, int DBNumber, int Start, int Size, byte[] Buffer);
AsDBWrite(int DBNumber, int Start, int Size, byte[] Buffer)1554         public int AsDBWrite(int DBNumber, int Start, int Size, byte[] Buffer)
1555         {
1556             return Cli_AsDBWrite(Client, DBNumber, Start, Size, Buffer);
1557         }
1558 
1559         [DllImport(S7Consts.Snap7LibName)]
Cli_AsMBRead(IntPtr Client, int Start, int Size, byte[] Buffer)1560         protected static extern int Cli_AsMBRead(IntPtr Client, int Start, int Size, byte[] Buffer);
AsMBRead(int Start, int Size, byte[] Buffer)1561         public int AsMBRead(int Start, int Size, byte[] Buffer)
1562         {
1563             return Cli_AsMBRead(Client, Start, Size, Buffer);
1564         }
1565 
1566         [DllImport(S7Consts.Snap7LibName)]
Cli_AsMBWrite(IntPtr Client, int Start, int Size, byte[] Buffer)1567         protected static extern int Cli_AsMBWrite(IntPtr Client, int Start, int Size, byte[] Buffer);
AsMBWrite(int Start, int Size, byte[] Buffer)1568         public int AsMBWrite(int Start, int Size, byte[] Buffer)
1569         {
1570             return Cli_AsMBWrite(Client, Start, Size, Buffer);
1571         }
1572 
1573         [DllImport(S7Consts.Snap7LibName)]
Cli_AsEBRead(IntPtr Client, int Start, int Size, byte[] Buffer)1574         protected static extern int Cli_AsEBRead(IntPtr Client, int Start, int Size, byte[] Buffer);
AsEBRead(int Start, int Size, byte[] Buffer)1575         public int AsEBRead(int Start, int Size, byte[] Buffer)
1576         {
1577             return Cli_AsEBRead(Client, Start, Size, Buffer);
1578         }
1579 
1580         [DllImport(S7Consts.Snap7LibName)]
Cli_AsEBWrite(IntPtr Client, int Start, int Size, byte[] Buffer)1581         protected static extern int Cli_AsEBWrite(IntPtr Client, int Start, int Size, byte[] Buffer);
AsEBWrite(int Start, int Size, byte[] Buffer)1582         public int AsEBWrite(int Start, int Size, byte[] Buffer)
1583         {
1584             return Cli_AsEBWrite(Client, Start, Size, Buffer);
1585         }
1586 
1587         [DllImport(S7Consts.Snap7LibName)]
Cli_AsABRead(IntPtr Client, int Start, int Size, byte[] Buffer)1588         protected static extern int Cli_AsABRead(IntPtr Client, int Start, int Size, byte[] Buffer);
AsABRead(int Start, int Size, byte[] Buffer)1589         public int AsABRead(int Start, int Size, byte[] Buffer)
1590         {
1591             return Cli_AsABRead(Client, Start, Size, Buffer);
1592         }
1593 
1594         [DllImport(S7Consts.Snap7LibName)]
Cli_AsABWrite(IntPtr Client, int Start, int Size, byte[] Buffer)1595         protected static extern int Cli_AsABWrite(IntPtr Client, int Start, int Size, byte[] Buffer);
AsABWrite(int Start, int Size, byte[] Buffer)1596         public int AsABWrite(int Start, int Size, byte[] Buffer)
1597         {
1598             return Cli_AsABWrite(Client, Start, Size, Buffer);
1599         }
1600 
1601         [DllImport(S7Consts.Snap7LibName)]
Cli_AsTMRead(IntPtr Client, int Start, int Amount, ushort[] Buffer)1602         protected static extern int Cli_AsTMRead(IntPtr Client, int Start, int Amount, ushort[] Buffer);
AsTMRead(int Start, int Amount, ushort[] Buffer)1603         public int AsTMRead(int Start, int Amount, ushort[] Buffer)
1604         {
1605             return Cli_AsTMRead(Client, Start, Amount, Buffer);
1606         }
1607 
1608         [DllImport(S7Consts.Snap7LibName)]
Cli_AsTMWrite(IntPtr Client, int Start, int Amount, ushort[] Buffer)1609         protected static extern int Cli_AsTMWrite(IntPtr Client, int Start, int Amount, ushort[] Buffer);
AsTMWrite(int Start, int Amount, ushort[] Buffer)1610         public int AsTMWrite(int Start, int Amount, ushort[] Buffer)
1611         {
1612             return Cli_AsTMWrite(Client, Start, Amount, Buffer);
1613         }
1614 
1615         [DllImport(S7Consts.Snap7LibName)]
Cli_AsCTRead(IntPtr Client, int Start, int Amount, ushort[] Buffer)1616         protected static extern int Cli_AsCTRead(IntPtr Client, int Start, int Amount, ushort[] Buffer);
AsCTRead(int Start, int Amount, ushort[] Buffer)1617         public int AsCTRead(int Start, int Amount, ushort[] Buffer)
1618         {
1619             return Cli_AsCTRead(Client, Start, Amount, Buffer);
1620         }
1621 
1622         [DllImport(S7Consts.Snap7LibName)]
Cli_AsCTWrite(IntPtr Client, int Start, int Amount, ushort[] Buffer)1623         protected static extern int Cli_AsCTWrite(IntPtr Client, int Start, int Amount, ushort[] Buffer);
AsCTWrite(int Start, int Amount, ushort[] Buffer)1624         public int AsCTWrite(int Start, int Amount, ushort[] Buffer)
1625         {
1626             return Cli_AsCTWrite(Client, Start, Amount, Buffer);
1627         }
1628 
1629         [DllImport(S7Consts.Snap7LibName)]
Cli_AsListBlocksOfType(IntPtr Client, Int32 BlockType, ushort[] List)1630         protected static extern int Cli_AsListBlocksOfType(IntPtr Client, Int32 BlockType, ushort[] List);
AsListBlocksOfType(int BlockType, ushort[] List)1631         public int AsListBlocksOfType(int BlockType, ushort[] List)
1632         {
1633             return Cli_AsListBlocksOfType(Client, BlockType, List);
1634         }
1635 
1636         [DllImport(S7Consts.Snap7LibName)]
Cli_AsReadSZL(IntPtr Client, int ID, int Index, ref S7SZL Data, ref Int32 Size)1637         protected static extern int Cli_AsReadSZL(IntPtr Client, int ID, int Index, ref S7SZL Data, ref Int32 Size);
AsReadSZL(int ID, int Index, ref S7SZL Data, ref Int32 Size)1638         public int AsReadSZL(int ID, int Index, ref S7SZL Data, ref Int32 Size)
1639         {
1640             return Cli_AsReadSZL(Client, ID, Index, ref Data, ref Size);
1641         }
1642 
1643         [DllImport(S7Consts.Snap7LibName)]
Cli_AsReadSZLList(IntPtr Client, ref S7SZLList List, ref Int32 ItemsCount)1644         protected static extern int Cli_AsReadSZLList(IntPtr Client, ref S7SZLList List, ref Int32 ItemsCount);
AsReadSZLList(ref S7SZLList List, ref Int32 ItemsCount)1645         public int AsReadSZLList(ref S7SZLList List, ref Int32 ItemsCount)
1646         {
1647             return Cli_AsReadSZLList(Client, ref List, ref ItemsCount);
1648         }
1649 
1650         [DllImport(S7Consts.Snap7LibName)]
Cli_AsUpload(IntPtr Client, int BlockType, int BlockNum, byte[] UsrData, ref int Size)1651         protected static extern int Cli_AsUpload(IntPtr Client, int BlockType, int BlockNum, byte[] UsrData, ref int Size);
AsUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)1652         public int AsUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)
1653         {
1654             return Cli_AsUpload(Client, BlockType, BlockNum, UsrData, ref Size);
1655         }
1656 
1657         [DllImport(S7Consts.Snap7LibName)]
Cli_AsFullUpload(IntPtr Client, int BlockType, int BlockNum, byte[] UsrData, ref int Size)1658         protected static extern int Cli_AsFullUpload(IntPtr Client, int BlockType, int BlockNum, byte[] UsrData, ref int Size);
AsFullUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)1659         public int AsFullUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)
1660         {
1661             return Cli_AsFullUpload(Client, BlockType, BlockNum, UsrData, ref Size);
1662         }
1663 
1664         [DllImport(S7Consts.Snap7LibName)]
Cli_AsDownload(IntPtr Client, int BlockNum, byte[] UsrData, int Size)1665         protected static extern int Cli_AsDownload(IntPtr Client, int BlockNum, byte[] UsrData, int Size);
ASDownload(int BlockNum, byte[] UsrData, int Size)1666         public int ASDownload(int BlockNum, byte[] UsrData, int Size)
1667         {
1668             return Cli_AsDownload(Client, BlockNum, UsrData, Size);
1669         }
1670 
1671         [DllImport(S7Consts.Snap7LibName)]
Cli_AsPlcCopyRamToRom(IntPtr Client, UInt32 Timeout)1672         protected static extern int Cli_AsPlcCopyRamToRom(IntPtr Client, UInt32 Timeout);
AsPlcCopyRamToRom(UInt32 Timeout)1673         public int AsPlcCopyRamToRom(UInt32 Timeout)
1674         {
1675             return Cli_AsPlcCopyRamToRom(Client, Timeout);
1676         }
1677 
1678         [DllImport(S7Consts.Snap7LibName)]
Cli_AsPlcCompress(IntPtr Client, UInt32 Timeout)1679         protected static extern int Cli_AsPlcCompress(IntPtr Client, UInt32 Timeout);
AsPlcCompress(UInt32 Timeout)1680         public int AsPlcCompress(UInt32 Timeout)
1681         {
1682             return Cli_AsPlcCompress(Client, Timeout);
1683         }
1684 
1685         [DllImport(S7Consts.Snap7LibName)]
Cli_AsDBGet(IntPtr Client, int DBNumber, byte[] UsrData, ref int Size)1686         protected static extern int Cli_AsDBGet(IntPtr Client, int DBNumber, byte[] UsrData, ref int Size);
AsDBGet(int DBNumber, byte[] UsrData, ref int Size)1687         public int AsDBGet(int DBNumber, byte[] UsrData, ref int Size)
1688         {
1689             return Cli_AsDBGet(Client, DBNumber, UsrData, ref Size);
1690         }
1691 
1692         [DllImport(S7Consts.Snap7LibName)]
Cli_AsDBFill(IntPtr Client, int DBNumber, int FillChar)1693         protected static extern int Cli_AsDBFill(IntPtr Client, int DBNumber, int FillChar);
AsDBFill(int DBNumber, int FillChar)1694         public int AsDBFill(int DBNumber, int FillChar)
1695         {
1696             return Cli_AsDBFill(Client, DBNumber, FillChar);
1697         }
1698 
1699         [DllImport(S7Consts.Snap7LibName)]
Cli_CheckAsCompletion(IntPtr Client, ref Int32 opResult)1700         protected static extern int Cli_CheckAsCompletion(IntPtr Client, ref Int32 opResult);
CheckAsCompletion(ref int opResult)1701         public bool CheckAsCompletion(ref int opResult)
1702         {
1703             return Cli_CheckAsCompletion(Client, ref opResult) == JobComplete;
1704         }
1705 
1706         [DllImport(S7Consts.Snap7LibName)]
Cli_WaitAsCompletion(IntPtr Client, Int32 Timeout)1707         protected static extern int Cli_WaitAsCompletion(IntPtr Client, Int32 Timeout);
WaitAsCompletion(int Timeout)1708         public int WaitAsCompletion(int Timeout)
1709         {
1710             return Cli_WaitAsCompletion(Client, Timeout);
1711         }
1712 
1713         #endregion
1714 
1715         #region [Info Functions]
1716 
1717         [DllImport(S7Consts.Snap7LibName)]
Cli_GetExecTime(IntPtr Client, ref UInt32 Time)1718         protected static extern int Cli_GetExecTime(IntPtr Client, ref UInt32 Time);
ExecTime()1719         public int ExecTime()
1720         {
1721             UInt32 Time = new UInt32();
1722             if (Cli_GetExecTime(Client, ref Time) == 0)
1723                 return (int)(Time);
1724             else
1725                 return -1;
1726         }
1727 
1728         [DllImport(S7Consts.Snap7LibName)]
Cli_GetLastError(IntPtr Client, ref Int32 LastError)1729         protected static extern int Cli_GetLastError(IntPtr Client, ref Int32 LastError);
LastError()1730         public int LastError()
1731         {
1732             Int32 ClientLastError = new Int32();
1733             if (Cli_GetLastError(Client, ref ClientLastError) == 0)
1734                 return (int)ClientLastError;
1735             else
1736                 return -1;
1737         }
1738 
1739         [DllImport(S7Consts.Snap7LibName)]
Cli_GetPduLength(IntPtr Client, ref Int32 Requested, ref Int32 Negotiated)1740         protected static extern int Cli_GetPduLength(IntPtr Client, ref Int32 Requested, ref Int32 Negotiated);
1741 
RequestedPduLength()1742         public int RequestedPduLength()
1743         {
1744             Int32 Requested = new Int32();
1745             Int32 Negotiated = new Int32();
1746             if (Cli_GetPduLength(Client, ref Requested, ref Negotiated) == 0)
1747                 return Requested;
1748             else
1749                 return -1;
1750         }
1751 
NegotiatedPduLength()1752         public int NegotiatedPduLength()
1753         {
1754             Int32 Requested = new Int32();
1755             Int32 Negotiated = new Int32();
1756             if (Cli_GetPduLength(Client, ref Requested, ref Negotiated) == 0)
1757                 return Negotiated;
1758             else
1759                 return -1;
1760         }
1761 
1762         [DllImport(S7Consts.Snap7LibName, CharSet = CharSet.Ansi)]
Cli_ErrorText(int Error, StringBuilder ErrMsg, int TextSize)1763         protected static extern int Cli_ErrorText(int Error, StringBuilder ErrMsg, int TextSize);
ErrorText(int Error)1764         public string ErrorText(int Error)
1765         {
1766             StringBuilder Message = new StringBuilder(MsgTextLen);
1767             Cli_ErrorText(Error, Message, MsgTextLen);
1768             return Message.ToString();
1769         }
1770 
1771         [DllImport(S7Consts.Snap7LibName)]
Cli_GetConnected(IntPtr Client, ref UInt32 IsConnected)1772         protected static extern int Cli_GetConnected(IntPtr Client, ref UInt32 IsConnected);
Connected()1773         public bool Connected()
1774         {
1775             UInt32 IsConnected = new UInt32();
1776             if (Cli_GetConnected(Client, ref IsConnected) == 0)
1777                 return IsConnected!=0;
1778             else
1779                 return false;
1780         }
1781 
1782         #endregion
1783     }
1784 
1785     public class S7Server
1786     {
1787         #region [Constants, private vars and TypeDefs]
1788 
1789         private const int MsgTextLen = 1024;
1790         private const int mkEvent = 0;
1791         private const int mkLog   = 1;
1792 
1793         // S7 Area ID
1794         public const byte S7AreaPE = 0x81;
1795         public const byte S7AreaPA = 0x82;
1796         public const byte S7AreaMK = 0x83;
1797         public const byte S7AreaDB = 0x84;
1798         public const byte S7AreaCT = 0x1C;
1799         public const byte S7AreaTM = 0x1D;
1800         // S7 Word Length
1801         public const int S7WLBit     = 0x01;
1802         public const int S7WLByte    = 0x02;
1803         public const int S7WLWord    = 0x04;
1804         public const int S7WLDWord   = 0x06;
1805         public const int S7WLReal    = 0x08;
1806         public const int S7WLCounter = 0x1C;
1807         public const int S7WLTimer   = 0x1D;
1808 
1809         // Server Area ID  (use with Register/unregister - Lock/unlock Area)
1810         public static readonly int srvAreaPE = 0;
1811         public static readonly int srvAreaPA = 1;
1812         public static readonly int srvAreaMK = 2;
1813         public static readonly int srvAreaCT = 3;
1814         public static readonly int srvAreaTM = 4;
1815         public static readonly int srvAreaDB = 5;
1816         // Errors
1817         public static readonly uint errSrvCannotStart        = 0x00100000; // Server cannot start
1818         public static readonly uint errSrvDBNullPointer      = 0x00200000; // Passed null as PData
1819         public static readonly uint errSrvAreaAlreadyExists  = 0x00300000; // Area Re-registration
1820         public static readonly uint errSrvUnknownArea        = 0x00400000; // Unknown area
1821         public static readonly uint errSrvInvalidParams      = 0x00500000; // Invalid param(s) supplied
1822         public static readonly uint errSrvTooManyDB          = 0x00600000; // Cannot register DB
1823         public static readonly uint errSrvInvalidParamNumber = 0x00700000; // Invalid param (srv_get/set_param)
1824         public static readonly uint errSrvCannotChangeParam  = 0x00800000; // Cannot change because running
1825         // TCP Server Event codes
1826         public static readonly uint evcServerStarted       = 0x00000001;
1827         public static readonly uint evcServerStopped       = 0x00000002;
1828         public static readonly uint evcListenerCannotStart = 0x00000004;
1829         public static readonly uint evcClientAdded         = 0x00000008;
1830         public static readonly uint evcClientRejected      = 0x00000010;
1831         public static readonly uint evcClientNoRoom        = 0x00000020;
1832         public static readonly uint evcClientException     = 0x00000040;
1833         public static readonly uint evcClientDisconnected  = 0x00000080;
1834         public static readonly uint evcClientTerminated    = 0x00000100;
1835         public static readonly uint evcClientsDropped      = 0x00000200;
1836         public static readonly uint evcReserved_00000400   = 0x00000400; // actually unused
1837         public static readonly uint evcReserved_00000800   = 0x00000800; // actually unused
1838         public static readonly uint evcReserved_00001000   = 0x00001000; // actually unused
1839         public static readonly uint evcReserved_00002000   = 0x00002000; // actually unused
1840         public static readonly uint evcReserved_00004000   = 0x00004000; // actually unused
1841         public static readonly uint evcReserved_00008000   = 0x00008000; // actually unused
1842         // S7 Server Event Code
1843         public static readonly uint evcPDUincoming         = 0x00010000;
1844         public static readonly uint evcDataRead            = 0x00020000;
1845         public static readonly uint evcDataWrite           = 0x00040000;
1846         public static readonly uint evcNegotiatePDU        = 0x00080000;
1847         public static readonly uint evcReadSZL             = 0x00100000;
1848         public static readonly uint evcClock               = 0x00200000;
1849         public static readonly uint evcUpload              = 0x00400000;
1850         public static readonly uint evcDownload            = 0x00800000;
1851         public static readonly uint evcDirectory           = 0x01000000;
1852         public static readonly uint evcSecurity            = 0x02000000;
1853         public static readonly uint evcControl             = 0x04000000;
1854         public static readonly uint evcReserved_08000000   = 0x08000000; // actually unused
1855         public static readonly uint evcReserved_10000000   = 0x10000000; // actually unused
1856         public static readonly uint evcReserved_20000000   = 0x20000000; // actually unused
1857         public static readonly uint evcReserved_40000000   = 0x40000000; // actually unused
1858         public static readonly uint evcReserved_80000000   = 0x80000000; // actually unused
1859         // Masks to enable/disable all events
1860         public static readonly uint evcAll  = 0xFFFFFFFF;
1861         public static readonly uint evcNone = 0x00000000;
1862         // Event SubCodes
1863         public static readonly ushort evsUnknown       = 0x0000;
1864         public static readonly ushort evsStartUpload   = 0x0001;
1865         public static readonly ushort evsStartDownload = 0x0001;
1866         public static readonly ushort evsGetBlockList  = 0x0001;
1867         public static readonly ushort evsStartListBoT  = 0x0002;
1868         public static readonly ushort evsListBoT       = 0x0003;
1869         public static readonly ushort evsGetBlockInfo  = 0x0004;
1870         public static readonly ushort evsGetClock      = 0x0001;
1871         public static readonly ushort evsSetClock      = 0x0002;
1872         public static readonly ushort evsSetPassword   = 0x0001;
1873         public static readonly ushort evsClrPassword   = 0x0002;
1874         // Event Params : functions group
1875         public static readonly ushort grProgrammer     = 0x0041;
1876         public static readonly ushort grCyclicData     = 0x0042;
1877         public static readonly ushort grBlocksInfo     = 0x0043;
1878         public static readonly ushort grSZL            = 0x0044;
1879         public static readonly ushort grPassword       = 0x0045;
1880         public static readonly ushort grBSend          = 0x0046;
1881         public static readonly ushort grClock          = 0x0047;
1882         public static readonly ushort grSecurity       = 0x0045;
1883         // Event Params : control codes
1884         public static readonly ushort CodeControlUnknown   = 0x0000;
1885         public static readonly ushort CodeControlColdStart = 0x0001;
1886         public static readonly ushort CodeControlWarmStart = 0x0002;
1887         public static readonly ushort CodeControlStop      = 0x0003;
1888         public static readonly ushort CodeControlCompress  = 0x0004;
1889         public static readonly ushort CodeControlCpyRamRom = 0x0005;
1890         public static readonly ushort CodeControlInsDel    = 0x0006;
1891         // Event Result
1892         public static readonly ushort evrNoError = 0x0000;
1893         public static readonly ushort evrFragmentRejected  = 0x0001;
1894         public static readonly ushort evrMalformedPDU      = 0x0002;
1895         public static readonly ushort evrSparseBytes       = 0x0003;
1896         public static readonly ushort evrCannotHandlePDU   = 0x0004;
1897         public static readonly ushort evrNotImplemented    = 0x0005;
1898         public static readonly ushort evrErrException      = 0x0006;
1899         public static readonly ushort evrErrAreaNotFound   = 0x0007;
1900         public static readonly ushort evrErrOutOfRange     = 0x0008;
1901         public static readonly ushort evrErrOverPDU        = 0x0009;
1902         public static readonly ushort evrErrTransportSize  = 0x000A;
1903         public static readonly ushort evrInvalidGroupUData = 0x000B;
1904         public static readonly ushort evrInvalidSZL        = 0x000C;
1905         public static readonly ushort evrDataSizeMismatch  = 0x000D;
1906         public static readonly ushort evrCannotUpload      = 0x000E;
1907         public static readonly ushort evrCannotDownload    = 0x000F;
1908         public static readonly ushort evrUploadInvalidID   = 0x0010;
1909         public static readonly ushort evrResNotFound       = 0x0011;
1910 
1911         // Read/Write Operation (to be used into RWCallback)
1912         public static readonly int OperationRead  = 0;
1913         public static readonly int OperationWrite = 1;
1914 
1915         [StructLayout(LayoutKind.Sequential, Pack = 1)]
1916         public struct USrvEvent
1917         {
1918             public IntPtr EvtTime;   // It's platform dependent (32 or 64 bit)
1919             public Int32  EvtSender;
1920             public UInt32 EvtCode;
1921             public ushort EvtRetCode;
1922             public ushort EvtParam1;
1923             public ushort EvtParam2;
1924             public ushort EvtParam3;
1925             public ushort EvtParam4;
1926         }
1927 
1928         public struct SrvEvent
1929         {
1930             public DateTime EvtTime;
1931             public Int32  EvtSender;
1932             public UInt32 EvtCode;
1933             public ushort EvtRetCode;
1934             public ushort EvtParam1;
1935             public ushort EvtParam2;
1936             public ushort EvtParam3;
1937             public ushort EvtParam4;
1938         }
1939 
1940         private Dictionary<Int32, GCHandle> HArea;
1941 
1942         private IntPtr Server;
1943 
1944         #endregion
1945 
1946         #region [Class Control]
1947 
1948         [DllImport(S7Consts.Snap7LibName)]
Srv_Create()1949         protected static extern IntPtr Srv_Create();
S7Server()1950         public S7Server()
1951         {
1952             Server = Srv_Create();
1953             HArea = new Dictionary<int,GCHandle>();
1954         }
1955 
1956         [DllImport(S7Consts.Snap7LibName)]
Srv_Destroy(ref IntPtr Server)1957         protected static extern int Srv_Destroy(ref IntPtr Server);
~S7Server()1958         ~S7Server()
1959         {
1960             foreach(var Item in HArea)
1961             {
1962                 GCHandle handle = Item.Value;
1963                 if (handle!=null)
1964                     handle.Free();
1965             }
1966             Srv_Destroy(ref Server);
1967         }
1968 
1969         [DllImport(S7Consts.Snap7LibName)]
Srv_StartTo(IntPtr Server, [MarshalAs(UnmanagedType.LPStr)] string Address)1970         protected static extern int Srv_StartTo(IntPtr Server, [MarshalAs(UnmanagedType.LPStr)] string Address);
StartTo(string Address)1971         public int StartTo(string Address)
1972         {
1973             return Srv_StartTo(Server, Address);
1974         }
1975 
1976         [DllImport(S7Consts.Snap7LibName)]
Srv_Start(IntPtr Server)1977         protected static extern int Srv_Start(IntPtr Server);
Start()1978         public int Start()
1979         {
1980             return Srv_Start(Server);
1981         }
1982 
1983         [DllImport(S7Consts.Snap7LibName)]
Srv_Stop(IntPtr Server)1984         protected static extern int Srv_Stop(IntPtr Server);
Stop()1985         public int Stop()
1986         {
1987             return Srv_Stop(Server);
1988         }
1989 
1990         // Get/SetParam needs a void* parameter, internally it decides the kind of pointer
1991         // in accord to ParamNumber.
1992         // To avoid the use of unsafe code we split the DLL functions and use overloaded methods.
1993 
1994         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_GetParam")]
Srv_GetParam_i16(IntPtr Server, Int32 ParamNumber, ref Int16 IntValue)1995         protected static extern int Srv_GetParam_i16(IntPtr Server, Int32 ParamNumber, ref Int16 IntValue);
GetParam(Int32 ParamNumber, ref Int16 IntValue)1996         public int GetParam(Int32 ParamNumber, ref Int16 IntValue)
1997         {
1998             return Srv_GetParam_i16(Server, ParamNumber, ref IntValue);
1999         }
2000 
2001         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_GetParam")]
Srv_GetParam_u16(IntPtr Server, Int32 ParamNumber, ref UInt16 IntValue)2002         protected static extern int Srv_GetParam_u16(IntPtr Server, Int32 ParamNumber, ref UInt16 IntValue);
GetParam(Int32 ParamNumber, ref UInt16 IntValue)2003         public int GetParam(Int32 ParamNumber, ref UInt16 IntValue)
2004         {
2005             return Srv_GetParam_u16(Server, ParamNumber, ref IntValue);
2006         }
2007 
2008         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_GetParam")]
Srv_GetParam_i32(IntPtr Server, Int32 ParamNumber, ref Int32 IntValue)2009         protected static extern int Srv_GetParam_i32(IntPtr Server, Int32 ParamNumber, ref Int32 IntValue);
GetParam(Int32 ParamNumber, ref Int32 IntValue)2010         public int GetParam(Int32 ParamNumber, ref Int32 IntValue)
2011         {
2012             return Srv_GetParam_i32(Server, ParamNumber, ref IntValue);
2013         }
2014 
2015         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_GetParam")]
Srv_GetParam_u32(IntPtr Server, Int32 ParamNumber, ref UInt32 IntValue)2016         protected static extern int Srv_GetParam_u32(IntPtr Server, Int32 ParamNumber, ref UInt32 IntValue);
GetParam(Int32 ParamNumber, ref UInt32 IntValue)2017         public int GetParam(Int32 ParamNumber, ref UInt32 IntValue)
2018         {
2019             return Srv_GetParam_u32(Server, ParamNumber, ref IntValue);
2020         }
2021 
2022         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_GetParam")]
Srv_GetParam_i64(IntPtr Server, Int32 ParamNumber, ref Int64 IntValue)2023         protected static extern int Srv_GetParam_i64(IntPtr Server, Int32 ParamNumber, ref Int64 IntValue);
GetParam(Int32 ParamNumber, ref Int64 IntValue)2024         public int GetParam(Int32 ParamNumber, ref Int64 IntValue)
2025         {
2026             return Srv_GetParam_i64(Server, ParamNumber, ref IntValue);
2027         }
2028 
2029         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_GetParam")]
Srv_GetParam_u64(IntPtr Server, Int32 ParamNumber, ref UInt64 IntValue)2030         protected static extern int Srv_GetParam_u64(IntPtr Server, Int32 ParamNumber, ref UInt64 IntValue);
GetParam(Int32 ParamNumber, ref UInt64 IntValue)2031         public int GetParam(Int32 ParamNumber, ref UInt64 IntValue)
2032         {
2033             return Srv_GetParam_u64(Server, ParamNumber, ref IntValue);
2034         }
2035 
2036         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_SetParam")]
Srv_SetParam_i16(IntPtr Server, Int32 ParamNumber, ref Int16 IntValue)2037         protected static extern int Srv_SetParam_i16(IntPtr Server, Int32 ParamNumber, ref Int16 IntValue);
SetParam(Int32 ParamNumber, ref Int16 IntValue)2038         public int SetParam(Int32 ParamNumber, ref Int16 IntValue)
2039         {
2040             return Srv_SetParam_i16(Server, ParamNumber, ref IntValue);
2041         }
2042 
2043         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_SetParam")]
Srv_SetParam_u16(IntPtr Server, Int32 ParamNumber, ref UInt16 IntValue)2044         protected static extern int Srv_SetParam_u16(IntPtr Server, Int32 ParamNumber, ref UInt16 IntValue);
SetParam(Int32 ParamNumber, ref UInt16 IntValue)2045         public int SetParam(Int32 ParamNumber, ref UInt16 IntValue)
2046         {
2047             return Srv_SetParam_u16(Server, ParamNumber, ref IntValue);
2048         }
2049 
2050         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_SetParam")]
Srv_SetParam_i32(IntPtr Server, Int32 ParamNumber, ref Int32 IntValue)2051         protected static extern int Srv_SetParam_i32(IntPtr Server, Int32 ParamNumber, ref Int32 IntValue);
SetParam(Int32 ParamNumber, ref Int32 IntValue)2052         public int SetParam(Int32 ParamNumber, ref Int32 IntValue)
2053         {
2054             return Srv_SetParam_i32(Server, ParamNumber, ref IntValue);
2055         }
2056 
2057         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_SetParam")]
Srv_SetParam_u32(IntPtr Server, Int32 ParamNumber, ref UInt32 IntValue)2058         protected static extern int Srv_SetParam_u32(IntPtr Server, Int32 ParamNumber, ref UInt32 IntValue);
SetParam(Int32 ParamNumber, ref UInt32 IntValue)2059         public int SetParam(Int32 ParamNumber, ref UInt32 IntValue)
2060         {
2061             return Srv_SetParam_u32(Server, ParamNumber, ref IntValue);
2062         }
2063 
2064         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_SetParam")]
Srv_SetParam_i64(IntPtr Server, Int32 ParamNumber, ref Int64 IntValue)2065         protected static extern int Srv_SetParam_i64(IntPtr Server, Int32 ParamNumber, ref Int64 IntValue);
SetParam(Int32 ParamNumber, ref Int64 IntValue)2066         public int SetParam(Int32 ParamNumber, ref Int64 IntValue)
2067         {
2068             return Srv_SetParam_i64(Server, ParamNumber, ref IntValue);
2069         }
2070 
2071         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Srv_SetParam")]
Srv_SetParam_u64(IntPtr Server, Int32 ParamNumber, ref UInt64 IntValue)2072         protected static extern int Srv_SetParam_u64(IntPtr Server, Int32 ParamNumber, ref UInt64 IntValue);
SetParam(Int32 ParamNumber, ref UInt64 IntValue)2073         public int SetParam(Int32 ParamNumber, ref UInt64 IntValue)
2074         {
2075             return Srv_SetParam_u64(Server, ParamNumber, ref IntValue);
2076         }
2077 
2078         #endregion
2079 
2080         #region [Data Areas functions]
2081 
2082         [DllImport(S7Consts.Snap7LibName)]
Srv_RegisterArea(IntPtr Server, Int32 AreaCode, Int32 Index, IntPtr pUsrData, Int32 Size)2083         protected static extern int Srv_RegisterArea(IntPtr Server, Int32 AreaCode, Int32 Index, IntPtr pUsrData, Int32 Size);
RegisterArea(Int32 AreaCode, Int32 Index, ref T pUsrData, Int32 Size)2084         public int RegisterArea<T>(Int32 AreaCode, Int32 Index, ref T pUsrData, Int32 Size)
2085         {
2086             Int32 AreaUID = (AreaCode << 16) + Index;
2087             GCHandle handle = GCHandle.Alloc(pUsrData, GCHandleType.Pinned);
2088             int Result = Srv_RegisterArea(Server, AreaCode, Index, handle.AddrOfPinnedObject(), Size);
2089             if (Result == 0)
2090                 HArea.Add(AreaUID, handle);
2091             else
2092                 handle.Free();
2093             return Result;
2094         }
2095 
2096         [DllImport(S7Consts.Snap7LibName)]
Srv_UnregisterArea(IntPtr Server, Int32 AreaCode, Int32 Index)2097         protected static extern int Srv_UnregisterArea(IntPtr Server, Int32 AreaCode, Int32 Index);
UnregisterArea(Int32 AreaCode, Int32 Index)2098         public int UnregisterArea(Int32 AreaCode, Int32 Index)
2099         {
2100             int Result = Srv_UnregisterArea(Server, AreaCode, Index);
2101             if (Result == 0)
2102             {
2103                 Int32 AreaUID = (AreaCode << 16) + Index;
2104                 if (HArea.ContainsKey(AreaUID)) // should be always true
2105                 {
2106                     GCHandle handle = HArea[AreaUID];
2107                     if (handle!=null) // should be always true
2108                         handle.Free();
2109                     HArea.Remove(AreaUID);
2110                 }
2111             }
2112             return Result;
2113         }
2114 
2115         [DllImport(S7Consts.Snap7LibName)]
Srv_LockArea(IntPtr Server, Int32 AreaCode, Int32 Index)2116         protected static extern int Srv_LockArea(IntPtr Server, Int32 AreaCode, Int32 Index);
LockArea(Int32 AreaCode, Int32 Index)2117         public int LockArea(Int32 AreaCode, Int32 Index)
2118         {
2119             return Srv_LockArea(Server, AreaCode, Index);
2120         }
2121 
2122         [DllImport(S7Consts.Snap7LibName)]
Srv_UnlockArea(IntPtr Server, Int32 AreaCode, Int32 Index)2123         protected static extern int Srv_UnlockArea(IntPtr Server, Int32 AreaCode, Int32 Index);
UnlockArea(Int32 AreaCode, Int32 Index)2124         public int UnlockArea(Int32 AreaCode, Int32 Index)
2125         {
2126             return Srv_UnlockArea(Server, AreaCode, Index);
2127         }
2128 
2129         #endregion
2130 
2131         #region [Notification functions (Events)]
2132 
2133         [StructLayout(LayoutKind.Sequential, Pack = 1)]
2134         public struct RWBuffer
2135         {
2136             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)] // A telegram cannot exceed PDU size (960 bytes)
2137             public byte[] Data;
2138         }
2139 
TSrvCallback(IntPtr usrPtr, ref USrvEvent Event, int Size)2140         public delegate void TSrvCallback(IntPtr usrPtr, ref USrvEvent Event, int Size);
TSrvRWAreaCallback(IntPtr usrPtr, int Sender, int Operation, ref S7Consts.S7Tag Tag, ref RWBuffer Buffer)2141         public delegate int TSrvRWAreaCallback(IntPtr usrPtr, int Sender, int Operation, ref S7Consts.S7Tag Tag, ref RWBuffer Buffer);
2142 
2143         [DllImport(S7Consts.Snap7LibName)]
Srv_SetEventsCallback(IntPtr Server, TSrvCallback Callback, IntPtr usrPtr)2144         protected static extern int Srv_SetEventsCallback(IntPtr Server, TSrvCallback Callback, IntPtr usrPtr);
SetEventsCallBack(TSrvCallback Callback, IntPtr usrPtr)2145         public int SetEventsCallBack(TSrvCallback Callback, IntPtr usrPtr)
2146         {
2147             return Srv_SetEventsCallback(Server, Callback, usrPtr);
2148         }
2149 
2150         [DllImport(S7Consts.Snap7LibName)]
Srv_SetReadEventsCallback(IntPtr Server, TSrvCallback Callback, IntPtr usrPtr)2151         protected static extern int Srv_SetReadEventsCallback(IntPtr Server, TSrvCallback Callback, IntPtr usrPtr);
SetReadEventsCallBack(TSrvCallback Callback, IntPtr usrPtr)2152         public int SetReadEventsCallBack(TSrvCallback Callback, IntPtr usrPtr)
2153         {
2154             return Srv_SetReadEventsCallback(Server, Callback, usrPtr);
2155         }
2156 
2157         [DllImport(S7Consts.Snap7LibName)]
Srv_SetRWAreaCallback(IntPtr Server, TSrvRWAreaCallback Callback, IntPtr usrPtr)2158         protected static extern int Srv_SetRWAreaCallback(IntPtr Server, TSrvRWAreaCallback Callback, IntPtr usrPtr);
SetRWAreaCallBack(TSrvRWAreaCallback Callback, IntPtr usrPtr)2159         public int SetRWAreaCallBack(TSrvRWAreaCallback Callback, IntPtr usrPtr)
2160         {
2161             return Srv_SetRWAreaCallback(Server, Callback, usrPtr);
2162         }
2163 
2164         [DllImport(S7Consts.Snap7LibName)]
Srv_PickEvent(IntPtr Server, ref USrvEvent Event, ref Int32 EvtReady)2165         protected static extern int Srv_PickEvent(IntPtr Server, ref USrvEvent Event, ref Int32 EvtReady);
PickEvent(ref USrvEvent Event)2166         public bool PickEvent(ref USrvEvent Event)
2167         {
2168             Int32 EvtReady = new Int32();
2169             if (Srv_PickEvent(Server, ref Event, ref EvtReady) == 0)
2170                 return EvtReady != 0;
2171             else
2172                 return false;
2173         }
2174 
2175         [DllImport(S7Consts.Snap7LibName)]
Srv_ClearEvents(IntPtr Server)2176         protected static extern int Srv_ClearEvents(IntPtr Server);
ClearEvents()2177         public int ClearEvents()
2178         {
2179             return Srv_ClearEvents(Server);
2180         }
2181 
2182         [DllImport(S7Consts.Snap7LibName, CharSet = CharSet.Ansi)]
Srv_EventText(ref USrvEvent Event, StringBuilder EvtMsg, int TextSize)2183         protected static extern int Srv_EventText(ref USrvEvent Event, StringBuilder EvtMsg, int TextSize);
EventText(ref USrvEvent Event)2184         public string EventText(ref USrvEvent Event)
2185         {
2186             StringBuilder Message = new StringBuilder(MsgTextLen);
2187             Srv_EventText(ref Event, Message, MsgTextLen);
2188             return Message.ToString();
2189         }
2190 
EvtTimeToDateTime(IntPtr TimeStamp)2191         public DateTime EvtTimeToDateTime(IntPtr TimeStamp)
2192         {
2193             DateTime UnixStartEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
2194             return UnixStartEpoch.AddSeconds(Convert.ToDouble(TimeStamp));
2195         }
2196 
2197         [DllImport(S7Consts.Snap7LibName)]
Srv_GetMask(IntPtr Server, Int32 MaskKind, ref UInt32 Mask)2198         protected static extern int Srv_GetMask(IntPtr Server, Int32 MaskKind, ref UInt32 Mask);
2199         [DllImport(S7Consts.Snap7LibName)]
Srv_SetMask(IntPtr Server, Int32 MaskKind, UInt32 Mask)2200         protected static extern int Srv_SetMask(IntPtr Server, Int32 MaskKind, UInt32 Mask);
2201 
2202         // Property LogMask R/W
2203         public UInt32 LogMask {
2204             get
2205             {
2206                 UInt32 Mask = new UInt32();
2207                 if (Srv_GetMask(Server, S7Server.mkLog, ref Mask)==0)
2208                     return Mask;
2209                 else
2210                     return 0;
2211             }
2212             set
2213             {
2214                 Srv_SetMask(Server, S7Server.mkLog, value);
2215             }
2216         }
2217 
2218         // Property EventMask R/W
2219         public UInt32 EventMask
2220         {
2221             get
2222             {
2223                 UInt32 Mask = new UInt32();
2224                 if (Srv_GetMask(Server, S7Server.mkEvent, ref Mask) == 0)
2225                     return Mask;
2226                 else
2227                     return 0;
2228             }
2229             set
2230             {
2231                 Srv_SetMask(Server, S7Server.mkEvent, value);
2232             }
2233         }
2234 
2235 
2236         #endregion
2237 
2238         #region [Info functions]
2239 
2240         [DllImport(S7Consts.Snap7LibName)]
Srv_GetStatus(IntPtr Server, ref Int32 ServerStatus, ref Int32 CpuStatus, ref Int32 ClientsCount)2241         protected static extern int Srv_GetStatus(IntPtr Server, ref Int32 ServerStatus, ref Int32 CpuStatus, ref Int32 ClientsCount);
2242         [DllImport(S7Consts.Snap7LibName)]
Srv_SetCpuStatus(IntPtr Server, Int32 CpuStatus)2243         protected static extern int Srv_SetCpuStatus(IntPtr Server, Int32 CpuStatus);
2244 
2245         // Property Virtual CPU status R/W
2246         public int CpuStatus
2247         {
2248             get
2249             {
2250                 Int32 CStatus = new Int32();
2251                 Int32 SStatus = new Int32();
2252                 Int32 CCount  = new Int32();
2253 
2254                 if (Srv_GetStatus(Server, ref SStatus, ref CStatus, ref CCount) == 0)
2255                     return CStatus;
2256                 else
2257                     return -1;
2258             }
2259             set
2260             {
2261                 Srv_SetCpuStatus(Server, value);
2262             }
2263         }
2264 
2265         // Property Server Status Read Only
2266         public int ServerStatus
2267         {
2268             get
2269             {
2270                 Int32 CStatus = new Int32();
2271                 Int32 SStatus = new Int32();
2272                 Int32 CCount = new Int32();
2273                 if (Srv_GetStatus(Server, ref SStatus, ref CStatus, ref CCount) == 0)
2274                     return SStatus;
2275                 else
2276                     return -1;
2277             }
2278         }
2279 
2280         // Property Clients Count Read Only
2281         public int ClientsCount
2282         {
2283             get
2284             {
2285                 Int32 CStatus = new Int32();
2286                 Int32 SStatus = new Int32();
2287                 Int32 CCount = new Int32();
2288                 if (Srv_GetStatus(Server, ref CStatus, ref SStatus, ref CCount) == 0)
2289                     return CCount;
2290                 else
2291                     return -1;
2292             }
2293         }
2294 
2295         [DllImport(S7Consts.Snap7LibName, CharSet = CharSet.Ansi)]
Srv_ErrorText(int Error, StringBuilder ErrMsg, int TextSize)2296         protected static extern int Srv_ErrorText(int Error, StringBuilder ErrMsg, int TextSize);
ErrorText(int Error)2297         public string ErrorText(int Error)
2298         {
2299             StringBuilder Message = new StringBuilder(MsgTextLen);
2300             Srv_ErrorText(Error, Message, MsgTextLen);
2301             return Message.ToString();
2302         }
2303 
2304         #endregion
2305     }
2306 
2307     public class S7Partner
2308     {
2309         #region [Constants, private vars and TypeDefs]
2310 
2311         private const int MsgTextLen = 1024;
2312 
2313         // Status
2314         public static readonly int par_stopped    = 0;   // stopped
2315         public static readonly int par_connecting = 1;   // running and active connecting
2316         public static readonly int par_waiting    = 2;   // running and waiting for a connection
2317         public static readonly int par_linked     = 3;   // running and connected : linked
2318         public static readonly int par_sending    = 4;   // sending data
2319         public static readonly int par_receiving  = 5;   // receiving data
2320         public static readonly int par_binderror  = 6;   // error starting passive server
2321 
2322         // Errors
2323         public static readonly uint errParAddressInUse       = 0x00200000;
2324         public static readonly uint errParNoRoom             = 0x00300000;
2325         public static readonly uint errServerNoRoom          = 0x00400000;
2326         public static readonly uint errParInvalidParams      = 0x00500000;
2327         public static readonly uint errParNotLinked          = 0x00600000;
2328         public static readonly uint errParBusy               = 0x00700000;
2329         public static readonly uint errParFrameTimeout       = 0x00800000;
2330         public static readonly uint errParInvalidPDU         = 0x00900000;
2331         public static readonly uint errParSendTimeout        = 0x00A00000;
2332         public static readonly uint errParRecvTimeout        = 0x00B00000;
2333         public static readonly uint errParSendRefused        = 0x00C00000;
2334         public static readonly uint errParNegotiatingPDU     = 0x00D00000;
2335         public static readonly uint errParSendingBlock       = 0x00E00000;
2336         public static readonly uint errParRecvingBlock       = 0x00F00000;
2337         public static readonly uint errBindError             = 0x01000000;
2338         public static readonly uint errParDestroying         = 0x01100000;
2339         public static readonly uint errParInvalidParamNumber = 0x01200000;
2340         public static readonly uint errParCannotChangeParam  = 0x01300000;
2341 
2342         // Generic byte buffer structure, you may need to declare a more
2343         // specialistic one in your program.
2344         // It's used to cast the input pointer that cames from the callback.
2345         // See the passive partned demo and the delegate S7ParRecvCallback.
2346 
2347         [StructLayout(LayoutKind.Sequential, Pack = 1)]
2348         public struct S7Buffer
2349         {
2350             [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x8000)]
2351             public byte[] Data;
2352         }
2353 
2354         // Job status
2355         private const int JobComplete = 0;
2356         private const int JobPending  = 1;
2357 
2358         private IntPtr Partner;
2359 
2360         private Int32 parBytesSent;
2361         private Int32 parBytesRecv;
2362 	    private Int32 parSendErrors;
2363         private Int32 parRecvErrors;
2364 
2365         #endregion
2366 
2367         #region [Class Control]
2368 
2369         [DllImport(S7Consts.Snap7LibName)]
Par_Create(Int32 ParActive)2370         protected static extern IntPtr Par_Create(Int32 ParActive);
S7Partner(int Active)2371         public S7Partner(int Active)
2372         {
2373             Partner= Par_Create(Active);
2374         }
2375 
2376         [DllImport(S7Consts.Snap7LibName)]
Par_Destroy(ref IntPtr Partner)2377         protected static extern int Par_Destroy(ref IntPtr Partner);
~S7Partner()2378         ~S7Partner()
2379         {
2380             Par_Destroy(ref Partner);
2381         }
2382 
2383         [DllImport(S7Consts.Snap7LibName)]
Par_StartTo( IntPtr Partner, [MarshalAs(UnmanagedType.LPStr)] string LocalAddress, [MarshalAs(UnmanagedType.LPStr)] string RemoteAddress, UInt16 LocalTSAP, UInt16 RemoteTSAP)2384         protected static extern int Par_StartTo(
2385             IntPtr Partner,
2386             [MarshalAs(UnmanagedType.LPStr)] string LocalAddress,
2387             [MarshalAs(UnmanagedType.LPStr)] string RemoteAddress,
2388             UInt16 LocalTSAP,
2389             UInt16 RemoteTSAP);
2390 
StartTo( string LocalAddress, string RemoteAddress, UInt16 LocalTSAP, UInt16 RemoteTSAP)2391         public int StartTo(
2392             string LocalAddress,
2393             string RemoteAddress,
2394             UInt16 LocalTSAP,
2395             UInt16 RemoteTSAP)
2396         {
2397             return Par_StartTo(Partner, LocalAddress, RemoteAddress, LocalTSAP, RemoteTSAP);
2398         }
2399 
2400         [DllImport(S7Consts.Snap7LibName)]
Par_Start(IntPtr Partner)2401         protected static extern int Par_Start(IntPtr Partner);
Start()2402         public int Start()
2403         {
2404             return Par_Start(Partner);
2405         }
2406 
2407         [DllImport(S7Consts.Snap7LibName)]
Par_Stop(IntPtr Partner)2408         protected static extern int Par_Stop(IntPtr Partner);
Stop()2409         public int Stop()
2410         {
2411             return Par_Stop(Partner);
2412         }
2413 
2414         // Get/SetParam needs a void* parameter, internally it decides the kind of pointer
2415         // in accord to ParamNumber.
2416         // To avoid the use of unsafe code we split the DLL functions and use overloaded methods.
2417 
2418         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_GetParam")]
Par_GetParam_i16(IntPtr Partner, Int32 ParamNumber, ref Int16 IntValue)2419         protected static extern int Par_GetParam_i16(IntPtr Partner, Int32 ParamNumber, ref Int16 IntValue);
GetParam(Int32 ParamNumber, ref Int16 IntValue)2420         public int GetParam(Int32 ParamNumber, ref Int16 IntValue)
2421         {
2422             return Par_GetParam_i16(Partner, ParamNumber, ref IntValue);
2423         }
2424 
2425         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_GetParam")]
Par_GetParam_u16(IntPtr Partner, Int32 ParamNumber, ref UInt16 IntValue)2426         protected static extern int Par_GetParam_u16(IntPtr Partner, Int32 ParamNumber, ref UInt16 IntValue);
GetParam(Int32 ParamNumber, ref UInt16 IntValue)2427         public int GetParam(Int32 ParamNumber, ref UInt16 IntValue)
2428         {
2429             return Par_GetParam_u16(Partner, ParamNumber, ref IntValue);
2430         }
2431 
2432         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_GetParam")]
Par_GetParam_i32(IntPtr Partner, Int32 ParamNumber, ref Int32 IntValue)2433         protected static extern int Par_GetParam_i32(IntPtr Partner, Int32 ParamNumber, ref Int32 IntValue);
GetParam(Int32 ParamNumber, ref Int32 IntValue)2434         public int GetParam(Int32 ParamNumber, ref Int32 IntValue)
2435         {
2436             return Par_GetParam_i32(Partner, ParamNumber, ref IntValue);
2437         }
2438 
2439         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_GetParam")]
Par_GetParam_u32(IntPtr Partner, Int32 ParamNumber, ref UInt32 IntValue)2440         protected static extern int Par_GetParam_u32(IntPtr Partner, Int32 ParamNumber, ref UInt32 IntValue);
GetParam(Int32 ParamNumber, ref UInt32 IntValue)2441         public int GetParam(Int32 ParamNumber, ref UInt32 IntValue)
2442         {
2443             return Par_GetParam_u32(Partner, ParamNumber, ref IntValue);
2444         }
2445 
2446         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_GetParam")]
Par_GetParam_i64(IntPtr Partner, Int32 ParamNumber, ref Int64 IntValue)2447         protected static extern int Par_GetParam_i64(IntPtr Partner, Int32 ParamNumber, ref Int64 IntValue);
GetParam(Int32 ParamNumber, ref Int64 IntValue)2448         public int GetParam(Int32 ParamNumber, ref Int64 IntValue)
2449         {
2450             return Par_GetParam_i64(Partner, ParamNumber, ref IntValue);
2451         }
2452 
2453         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_GetParam")]
Par_GetParam_u64(IntPtr Partner, Int32 ParamNumber, ref UInt64 IntValue)2454         protected static extern int Par_GetParam_u64(IntPtr Partner, Int32 ParamNumber, ref UInt64 IntValue);
GetParam(Int32 ParamNumber, ref UInt64 IntValue)2455         public int GetParam(Int32 ParamNumber, ref UInt64 IntValue)
2456         {
2457             return Par_GetParam_u64(Partner, ParamNumber, ref IntValue);
2458         }
2459 
2460         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_SetParam")]
Par_SetParam_i16(IntPtr Partner, Int32 ParamNumber, ref Int16 IntValue)2461         protected static extern int Par_SetParam_i16(IntPtr Partner, Int32 ParamNumber, ref Int16 IntValue);
SetParam(Int32 ParamNumber, ref Int16 IntValue)2462         public int SetParam(Int32 ParamNumber, ref Int16 IntValue)
2463         {
2464             return Par_SetParam_i16(Partner, ParamNumber, ref IntValue);
2465         }
2466 
2467         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_SetParam")]
Par_SetParam_u16(IntPtr Partner, Int32 ParamNumber, ref UInt16 IntValue)2468         protected static extern int Par_SetParam_u16(IntPtr Partner, Int32 ParamNumber, ref UInt16 IntValue);
SetParam(Int32 ParamNumber, ref UInt16 IntValue)2469         public int SetParam(Int32 ParamNumber, ref UInt16 IntValue)
2470         {
2471             return Par_SetParam_u16(Partner, ParamNumber, ref IntValue);
2472         }
2473 
2474         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_SetParam")]
Par_SetParam_i32(IntPtr Partner, Int32 ParamNumber, ref Int32 IntValue)2475         protected static extern int Par_SetParam_i32(IntPtr Partner, Int32 ParamNumber, ref Int32 IntValue);
SetParam(Int32 ParamNumber, ref Int32 IntValue)2476         public int SetParam(Int32 ParamNumber, ref Int32 IntValue)
2477         {
2478             return Par_SetParam_i32(Partner, ParamNumber, ref IntValue);
2479         }
2480 
2481         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_SetParam")]
Par_SetParam_u32(IntPtr Partner, Int32 ParamNumber, ref UInt32 IntValue)2482         protected static extern int Par_SetParam_u32(IntPtr Partner, Int32 ParamNumber, ref UInt32 IntValue);
SetParam(Int32 ParamNumber, ref UInt32 IntValue)2483         public int SetParam(Int32 ParamNumber, ref UInt32 IntValue)
2484         {
2485             return Par_SetParam_u32(Partner, ParamNumber, ref IntValue);
2486         }
2487 
2488         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_SetParam")]
Par_SetParam_i64(IntPtr Partner, Int32 ParamNumber, ref Int64 IntValue)2489         protected static extern int Par_SetParam_i64(IntPtr Partner, Int32 ParamNumber, ref Int64 IntValue);
SetParam(Int32 ParamNumber, ref Int64 IntValue)2490         public int SetParam(Int32 ParamNumber, ref Int64 IntValue)
2491         {
2492             return Par_SetParam_i64(Partner, ParamNumber, ref IntValue);
2493         }
2494 
2495         [DllImport(S7Consts.Snap7LibName, EntryPoint = "Par_SetParam")]
Par_SetParam_u64(IntPtr Partner, Int32 ParamNumber, ref UInt64 IntValue)2496         protected static extern int Par_SetParam_u64(IntPtr Partner, Int32 ParamNumber, ref UInt64 IntValue);
SetParam(Int32 ParamNumber, ref UInt64 IntValue)2497         public int SetParam(Int32 ParamNumber, ref UInt64 IntValue)
2498         {
2499             return Par_SetParam_u64(Partner, ParamNumber, ref IntValue);
2500         }
2501 
2502         #endregion
2503 
2504         #region [Data I/O functions : BSend]
2505 
2506         [DllImport(S7Consts.Snap7LibName)]
Par_BSend(IntPtr Partner, UInt32 R_ID, byte[] Buffer, Int32 Size)2507         protected static extern int Par_BSend(IntPtr Partner, UInt32 R_ID, byte[] Buffer, Int32 Size);
BSend(UInt32 R_ID, byte[] Buffer, Int32 Size)2508         public int BSend(UInt32 R_ID, byte[] Buffer, Int32 Size)
2509         {
2510             return Par_BSend(Partner, R_ID, Buffer, Size);
2511         }
2512 
2513         [DllImport(S7Consts.Snap7LibName)]
Par_AsBSend(IntPtr Partner, UInt32 R_ID, byte[] Buffer, Int32 Size)2514         protected static extern int Par_AsBSend(IntPtr Partner, UInt32 R_ID, byte[] Buffer, Int32 Size);
AsBSend(UInt32 R_ID, byte[] Buffer, Int32 Size)2515         public int AsBSend(UInt32 R_ID, byte[] Buffer, Int32 Size)
2516         {
2517             return Par_AsBSend(Partner, R_ID, Buffer, Size);
2518         }
2519 
2520         [DllImport(S7Consts.Snap7LibName)]
Par_CheckAsBSendCompletion(IntPtr Partner, ref Int32 opResult)2521         protected static extern int Par_CheckAsBSendCompletion(IntPtr Partner, ref Int32 opResult);
CheckAsBSendCompletion(ref int opResult)2522         public bool CheckAsBSendCompletion(ref int opResult)
2523         {
2524             return Par_CheckAsBSendCompletion(Partner, ref opResult)==JobComplete;
2525         }
2526 
2527         [DllImport(S7Consts.Snap7LibName)]
Par_WaitAsBSendCompletion(IntPtr Partner, Int32 Timeout)2528         protected static extern int Par_WaitAsBSendCompletion(IntPtr Partner, Int32 Timeout);
WaitAsBSendCompletion(int Timeout)2529         public int WaitAsBSendCompletion(int Timeout)
2530         {
2531             return Par_WaitAsBSendCompletion(Partner, Timeout);
2532         }
2533 
S7ParSendCompletion(IntPtr usrPtr, int opResult)2534         public delegate void S7ParSendCompletion(IntPtr usrPtr, int opResult);
2535 
2536         [DllImport(S7Consts.Snap7LibName)]
Par_SetSendCallback(IntPtr Partner, S7ParSendCompletion Completion, IntPtr usrPtr)2537         protected static extern int Par_SetSendCallback(IntPtr Partner, S7ParSendCompletion Completion, IntPtr usrPtr);
SetSendCallBack(S7ParSendCompletion Completion, IntPtr usrPtr)2538         public int SetSendCallBack(S7ParSendCompletion Completion, IntPtr usrPtr)
2539         {
2540             return Par_SetSendCallback(Partner, Completion, usrPtr);
2541         }
2542 
2543         #endregion
2544 
2545         #region [Data I/O functions : BRecv]
2546 
2547         [DllImport(S7Consts.Snap7LibName)]
Par_BRecv(IntPtr Partner, ref UInt32 R_ID, byte[] Buffer, ref Int32 Size, UInt32 Timeout)2548         protected static extern int Par_BRecv(IntPtr Partner, ref UInt32 R_ID, byte[] Buffer, ref Int32 Size, UInt32 Timeout);
BRecv(ref UInt32 R_ID, byte[] Buffer, ref Int32 Size, UInt32 Timeout)2549         public int BRecv(ref UInt32 R_ID, byte[] Buffer, ref Int32 Size, UInt32 Timeout)
2550         {
2551             return Par_BRecv(Partner, ref R_ID, Buffer, ref Size, Timeout);
2552         }
2553 
2554         [DllImport(S7Consts.Snap7LibName)]
Par_CheckAsBRecvCompletion(IntPtr Partner, ref Int32 opResult, ref UInt32 R_ID, byte[] Buffer, ref Int32 Size)2555         protected static extern int Par_CheckAsBRecvCompletion(IntPtr Partner, ref Int32 opResult, ref UInt32 R_ID, byte[] Buffer, ref Int32 Size);
CheckAsBRecvCompletion(ref Int32 opResult, ref UInt32 R_ID, byte[] Buffer, ref Int32 Size)2556         public bool CheckAsBRecvCompletion(ref Int32 opResult, ref UInt32 R_ID, byte[] Buffer, ref Int32 Size)
2557         {
2558             Par_CheckAsBRecvCompletion(Partner, ref opResult, ref R_ID, Buffer, ref Size);
2559             return opResult == JobComplete;
2560         }
2561 
S7ParRecvCallback(IntPtr usrPtr, int opResult, uint R_ID, IntPtr pData, int Size)2562         public delegate void S7ParRecvCallback(IntPtr usrPtr, int opResult, uint R_ID, IntPtr pData, int Size);
2563 
2564         [DllImport(S7Consts.Snap7LibName)]
Par_SetRecvCallback(IntPtr Partner, S7ParRecvCallback Callback, IntPtr usrPtr)2565         protected static extern int Par_SetRecvCallback(IntPtr Partner, S7ParRecvCallback Callback, IntPtr usrPtr);
SetRecvCallback(S7ParRecvCallback Callback, IntPtr usrPtr)2566         public int SetRecvCallback(S7ParRecvCallback Callback, IntPtr usrPtr)
2567         {
2568             return Par_SetRecvCallback(Partner, Callback, usrPtr);
2569         }
2570 
2571         #endregion
2572 
2573         #region [Info functions]
2574 
2575         [DllImport(S7Consts.Snap7LibName)]
Par_GetLastError(IntPtr Partner, ref Int32 LastError)2576         protected static extern int Par_GetLastError(IntPtr Partner, ref Int32 LastError);
LastError(ref Int32 LastError)2577         public int LastError(ref Int32 LastError)
2578         {
2579             Int32 PartnerLastError = new Int32();
2580             if (Par_GetLastError(Partner, ref PartnerLastError) == 0)
2581                 return (int)PartnerLastError;
2582             else
2583                 return -1;
2584         }
2585 
2586         [DllImport(S7Consts.Snap7LibName, CharSet = CharSet.Ansi)]
Par_ErrorText(int Error, StringBuilder ErrMsg, int TextSize)2587         protected static extern int Par_ErrorText(int Error, StringBuilder ErrMsg, int TextSize);
ErrorText(int Error)2588         public string ErrorText(int Error)
2589         {
2590             StringBuilder Message = new StringBuilder(MsgTextLen);
2591             Par_ErrorText(Error, Message, MsgTextLen);
2592             return Message.ToString();
2593         }
2594 
2595         [DllImport(S7Consts.Snap7LibName)]
Par_GetStats(IntPtr Partner, ref Int32 BytesSent, ref Int32 BytesRecv, ref Int32 SendErrors, ref Int32 RecvErrors)2596         protected static extern int Par_GetStats(IntPtr Partner, ref Int32 BytesSent, ref Int32 BytesRecv,
2597 	       ref Int32 SendErrors, ref Int32 RecvErrors);
2598 
GetStatistics()2599         private void GetStatistics()
2600         {
2601             if (Par_GetStats(Partner, ref parBytesSent, ref parBytesRecv, ref parSendErrors, ref parRecvErrors) != 0)
2602             {
2603                 parBytesSent = -1;
2604                 parBytesRecv = -1;
2605                 parSendErrors = -1;
2606                 parRecvErrors = -1;
2607             }
2608         }
2609 
2610         public int BytesSent
2611         {
2612             get
2613             {
2614                 GetStatistics();
2615                 return parBytesSent;
2616             }
2617         }
2618 
2619         public int BytesRecv
2620         {
2621             get
2622             {
2623                 GetStatistics();
2624                 return parBytesRecv;
2625             }
2626         }
2627 
2628         public int SendErrors
2629         {
2630             get
2631             {
2632                 GetStatistics();
2633                 return parSendErrors;
2634             }
2635         }
2636 
2637         public int RecvErrors
2638         {
2639             get
2640             {
2641                 GetStatistics();
2642                 return parRecvErrors;
2643             }
2644         }
2645 
2646         [DllImport(S7Consts.Snap7LibName)]
Par_GetStatus(IntPtr Partner, ref Int32 Status)2647         protected static extern int Par_GetStatus(IntPtr Partner, ref Int32 Status);
2648 
2649         public int Status
2650         {
2651             get
2652             {
2653                 int ParStatus = new int();
2654                 if (Par_GetStatus(Partner, ref ParStatus) != 0)
2655                     return -1;
2656                 else
2657                     return ParStatus;
2658             }
2659         }
2660         // simply useful
2661         public bool Linked
2662         {
2663             get
2664             {
2665                 return Status == par_linked;
2666             }
2667         }
2668         #endregion
2669 
2670     }
2671 }
2672