-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sharp7.cs
3763 lines (3408 loc) · 128 KB
/
Sharp7.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*=============================================================================|
| PROJECT Sharp7 1.0.3 |
|==============================================================================|
| Copyright (C) 2016 Davide Nardella |
| All rights reserved. |
|==============================================================================|
| Sharp7 is free software: you can redistribute it and/or modify |
| it under the terms of the Lesser GNU General Public License as published by |
| the Free Software Foundation, either version 3 of the License, or |
| (at your option) any later version. |
| |
| It means that you can distribute your commercial software which includes |
| Sharp7 without the requirement to distribute the source code of your |
| application and without the requirement that your application be itself |
| distributed under LGPL. |
| |
| Sharp7 is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| Lesser GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License and a |
| copy of Lesser GNU General Public License along with Sharp7. |
| If not, see http://www.gnu.org/licenses/ |
|==============================================================================|
History:
* 1.0.0 2016/10/09 First Release
* 1.0.1 2016/10/22 Added CoreCLR compatibility (CORE_CLR symbol must be
defined in Build options).
Thanks to Dirk-Jan Wassink.
* 1.0.2 2016/11/13 Fixed a bug in CLR compatibility
* 1.0.3 2017/01/25 Fixed a bug in S7.GetIntAt(). Thanks to lupal1
Added S7Timer Read/Write. Thanks to Lukas Palkovic
*/
#define CORE_CLR
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Threading.Tasks;
//------------------------------------------------------------------------------
// If you are compiling for UWP verify that WINDOWS_UWP or NETFX_CORE are
// defined into Project Properties->Build->Conditional compilation symbols
//------------------------------------------------------------------------------
#if WINDOWS_UWP || NETFX_CORE
using System.Threading.Tasks;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
#else // <-- Including MONO
using System.Net.Sockets;
#endif
namespace Sharp7
{
#region [Async Sockets UWP(W10,IoT,Phone)/Windows 8/Windows 8 Phone]
#if WINDOWS_UWP || NETFX_CORE
class MsgSocket
{
private DataReader Reader = null;
private DataWriter Writer = null;
private StreamSocket TCPSocket;
private bool _Connected;
private int _ReadTimeout = 2000;
private int _WriteTimeout = 2000;
private int _ConnectTimeout = 1000;
public static int LastError = 0;
private void CreateSocket()
{
TCPSocket = new StreamSocket();
TCPSocket.Control.NoDelay = true;
_Connected = false;
}
public MsgSocket()
{
}
public void Close()
{
if (Reader != null)
{
Reader.Dispose();
Reader = null;
}
if (Writer != null)
{
Writer.Dispose();
Writer = null;
}
if (TCPSocket != null)
{
TCPSocket.Dispose();
TCPSocket = null;
}
_Connected = false;
}
private async Task AsConnect(string Host, string port, CancellationTokenSource cts)
{
HostName ServerHost = new HostName(Host);
try
{
await TCPSocket.ConnectAsync(ServerHost, port).AsTask(cts.Token);
_Connected = true;
}
catch (TaskCanceledException)
{
LastError = S7Consts.errTCPConnectionTimeout;
}
catch
{
LastError = S7Consts.errTCPConnectionFailed; // Maybe unreachable peer
}
}
public int Connect(string Host, int Port)
{
LastError = 0;
if (!Connected)
{
CreateSocket();
CancellationTokenSource cts = new CancellationTokenSource();
try
{
try
{
cts.CancelAfter(_ConnectTimeout);
Task.WaitAny(Task.Run(async () => await AsConnect(Host, Port.ToString(), cts)));
}
catch
{
LastError = S7Consts.errTCPConnectionFailed;
}
}
finally
{
if (cts != null)
{
try
{
cts.Cancel();
cts.Dispose();
cts = null;
}
catch { }
}
}
if (LastError == 0)
{
Reader = new DataReader(TCPSocket.InputStream);
Reader.InputStreamOptions = InputStreamOptions.Partial;
Writer = new DataWriter(TCPSocket.OutputStream);
_Connected = true;
}
else
Close();
}
return LastError;
}
private async Task AsReadBuffer(byte[] Buffer, int Size, CancellationTokenSource cts)
{
try
{
await Reader.LoadAsync((uint)Size).AsTask(cts.Token);
Reader.ReadBytes(Buffer);
}
catch
{
LastError = S7Consts.errTCPDataReceive;
}
}
public int Receive(byte[] Buffer, int Start, int Size)
{
byte[] InBuffer = new byte[Size];
CancellationTokenSource cts = new CancellationTokenSource();
LastError = 0;
try
{
try
{
cts.CancelAfter(_ReadTimeout);
Task.WaitAny(Task.Run(async () => await AsReadBuffer(InBuffer, Size, cts)));
}
catch
{
LastError = S7Consts.errTCPDataReceive;
}
}
finally
{
if (cts != null)
{
try
{
cts.Cancel();
cts.Dispose();
cts = null;
}
catch { }
}
}
if (LastError == 0)
Array.Copy(InBuffer, 0, Buffer, Start, Size);
else
Close();
return LastError;
}
private async Task WriteBuffer(byte[] Buffer, CancellationTokenSource cts)
{
try
{
Writer.WriteBytes(Buffer);
await Writer.StoreAsync().AsTask(cts.Token);
}
catch
{
LastError = S7Consts.errTCPDataSend;
}
}
public int Send(byte[] Buffer, int Size)
{
byte[] OutBuffer = new byte[Size];
CancellationTokenSource cts = new CancellationTokenSource();
Array.Copy(Buffer, 0, OutBuffer, 0, Size);
LastError = 0;
try
{
try
{
cts.CancelAfter(_WriteTimeout);
Task.WaitAny(Task.Run(async () => await WriteBuffer(OutBuffer, cts)));
}
catch
{
LastError = S7Consts.errTCPDataSend;
}
}
finally
{
if (cts != null)
{
try
{
cts.Cancel();
cts.Dispose();
cts = null;
}
catch { }
}
}
if (LastError != 0)
Close();
return LastError;
}
~MsgSocket()
{
Close();
}
public bool Connected
{
get
{
return (TCPSocket != null) && _Connected;
}
}
public int ReadTimeout
{
get
{
return _ReadTimeout;
}
set
{
_ReadTimeout = value;
}
}
public int WriteTimeout
{
get
{
return _WriteTimeout;
}
set
{
_WriteTimeout = value;
}
}
public int ConnectTimeout
{
get
{
return _ConnectTimeout;
}
set
{
_ConnectTimeout = value;
}
}
}
#endif
#endregion
#region [Sync Sockets Win32/Win64 Desktop Application]
#if !WINDOWS_UWP && !NETFX_CORE
class MsgSocket
{
private Socket TCPSocket;
private int _ReadTimeout = 2000;
private int _WriteTimeout = 2000;
private int _ConnectTimeout = 1000;
public int LastError = 0;
public MsgSocket()
{
}
~MsgSocket()
{
Close();
}
public void Close()
{
if (TCPSocket != null)
{
TCPSocket.Dispose();
TCPSocket = null;
}
}
private void CreateSocket()
{
TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TCPSocket.NoDelay = true;
}
private void TCPPing(string Host, int Port)
{
// To Ping the PLC an Asynchronous socket is used rather then an ICMP packet.
// This allows the use also across Internet and Firewalls (obviously the port must be opened)
LastError = 0;
Socket PingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
#if CORE_CLR
var task = PingSocket.ConnectAsync(Host, Port);
task.Wait(_ConnectTimeout);
bool success = task.IsCompleted;
#else
IAsyncResult result = PingSocket.BeginConnect(Host, Port, null, null);
bool success = result.AsyncWaitHandle.WaitOne(_ConnectTimeout, true);
#endif
if (!success)
{
LastError = S7Consts.errTCPConnectionFailed;
}
}
catch
{
LastError = S7Consts.errTCPConnectionFailed;
};
#if CORE_CLR
PingSocket.Dispose();
#else
PingSocket.Close();
#endif
}
public int Connect(string Host, int Port)
{
LastError = 0;
if (!Connected)
{
TCPPing(Host, Port);
if (LastError == 0)
try
{
CreateSocket();
TCPSocket.Connect(Host, Port);
}
catch
{
LastError = S7Consts.errTCPConnectionFailed;
}
}
return LastError;
}
private int WaitForData(int Size, int Timeout)
{
bool Expired = false;
int SizeAvail;
int Elapsed = Environment.TickCount;
LastError = 0;
try
{
SizeAvail = TCPSocket.Available;
while ((SizeAvail < Size) && (!Expired))
{
Task.Delay(2).Wait();
SizeAvail = TCPSocket.Available;
Expired = Environment.TickCount - Elapsed > Timeout;
// If timeout we clean the buffer
if (Expired && (SizeAvail > 0))
try
{
byte[] Flush = new byte[SizeAvail];
TCPSocket.Receive(Flush, 0, SizeAvail, SocketFlags.None);
}
catch { }
}
}
catch
{
LastError = S7Consts.errTCPDataReceive;
}
if (Expired)
{
LastError = S7Consts.errTCPDataReceive;
}
return LastError;
}
public int Receive(byte[] Buffer, int Start, int Size)
{
int BytesRead = 0;
LastError = WaitForData(Size, _ReadTimeout);
if (LastError == 0)
{
try
{
BytesRead = TCPSocket.Receive(Buffer, Start, Size, SocketFlags.None);
}
catch
{
LastError = S7Consts.errTCPDataReceive;
}
if (BytesRead == 0) // Connection Reset by the peer
{
LastError = S7Consts.errTCPDataReceive;
Close();
}
}
return LastError;
}
public int Send(byte[] Buffer, int Size)
{
LastError = 0;
try
{
int BytesSent = TCPSocket.Send(Buffer, Size, SocketFlags.None);
}
catch
{
LastError = S7Consts.errTCPDataSend;
Close();
}
return LastError;
}
public bool Connected
{
get
{
return (TCPSocket != null) && (TCPSocket.Connected);
}
}
public int ReadTimeout
{
get
{
return _ReadTimeout;
}
set
{
_ReadTimeout = value;
}
}
public int WriteTimeout
{
get
{
return _WriteTimeout;
}
set
{
_WriteTimeout = value;
}
}
public int ConnectTimeout
{
get
{
return _ConnectTimeout;
}
set
{
_ConnectTimeout = value;
}
}
}
#endif
#endregion
public static class S7Consts
{
#region [Exported Consts]
// Error codes
//------------------------------------------------------------------------------
// ERRORS
//------------------------------------------------------------------------------
public const int errTCPSocketCreation = 0x00000001;
public const int errTCPConnectionTimeout = 0x00000002;
public const int errTCPConnectionFailed = 0x00000003;
public const int errTCPReceiveTimeout = 0x00000004;
public const int errTCPDataReceive = 0x00000005;
public const int errTCPSendTimeout = 0x00000006;
public const int errTCPDataSend = 0x00000007;
public const int errTCPConnectionReset = 0x00000008;
public const int errTCPNotConnected = 0x00000009;
public const int errTCPUnreachableHost = 0x00002751;
public const int errIsoConnect = 0x00010000; // Connection error
public const int errIsoInvalidPDU = 0x00030000; // Bad format
public const int errIsoInvalidDataSize = 0x00040000; // Bad Datasize passed to send/recv : buffer is invalid
public const int errCliNegotiatingPDU = 0x00100000;
public const int errCliInvalidParams = 0x00200000;
public const int errCliJobPending = 0x00300000;
public const int errCliTooManyItems = 0x00400000;
public const int errCliInvalidWordLen = 0x00500000;
public const int errCliPartialDataWritten = 0x00600000;
public const int errCliSizeOverPDU = 0x00700000;
public const int errCliInvalidPlcAnswer = 0x00800000;
public const int errCliAddressOutOfRange = 0x00900000;
public const int errCliInvalidTransportSize = 0x00A00000;
public const int errCliWriteDataSizeMismatch = 0x00B00000;
public const int errCliItemNotAvailable = 0x00C00000;
public const int errCliInvalidValue = 0x00D00000;
public const int errCliCannotStartPLC = 0x00E00000;
public const int errCliAlreadyRun = 0x00F00000;
public const int errCliCannotStopPLC = 0x01000000;
public const int errCliCannotCopyRamToRom = 0x01100000;
public const int errCliCannotCompress = 0x01200000;
public const int errCliAlreadyStop = 0x01300000;
public const int errCliFunNotAvailable = 0x01400000;
public const int errCliUploadSequenceFailed = 0x01500000;
public const int errCliInvalidDataSizeRecvd = 0x01600000;
public const int errCliInvalidBlockType = 0x01700000;
public const int errCliInvalidBlockNumber = 0x01800000;
public const int errCliInvalidBlockSize = 0x01900000;
public const int errCliNeedPassword = 0x01D00000;
public const int errCliInvalidPassword = 0x01E00000;
public const int errCliNoPasswordToSetOrClear = 0x01F00000;
public const int errCliJobTimeout = 0x02000000;
public const int errCliPartialDataRead = 0x02100000;
public const int errCliBufferTooSmall = 0x02200000;
public const int errCliFunctionRefused = 0x02300000;
public const int errCliDestroying = 0x02400000;
public const int errCliInvalidParamNumber = 0x02500000;
public const int errCliCannotChangeParam = 0x02600000;
public const int errCliFunctionNotImplemented = 0x02700000;
//------------------------------------------------------------------------------
// PARAMS LIST FOR COMPATIBILITY WITH Snap7.net.cs
//------------------------------------------------------------------------------
public const Int32 p_u16_LocalPort = 1; // Not applicable here
public const Int32 p_u16_RemotePort = 2;
public const Int32 p_i32_PingTimeout = 3;
public const Int32 p_i32_SendTimeout = 4;
public const Int32 p_i32_RecvTimeout = 5;
public const Int32 p_i32_WorkInterval = 6; // Not applicable here
public const Int32 p_u16_SrcRef = 7; // Not applicable here
public const Int32 p_u16_DstRef = 8; // Not applicable here
public const Int32 p_u16_SrcTSap = 9; // Not applicable here
public const Int32 p_i32_PDURequest = 10;
public const Int32 p_i32_MaxClients = 11; // Not applicable here
public const Int32 p_i32_BSendTimeout = 12; // Not applicable here
public const Int32 p_i32_BRecvTimeout = 13; // Not applicable here
public const Int32 p_u32_RecoveryTime = 14; // Not applicable here
public const Int32 p_u32_KeepAliveTime = 15; // Not applicable here
// Area ID
public const byte S7AreaPE = 0x81;
public const byte S7AreaPA = 0x82;
public const byte S7AreaMK = 0x83;
public const byte S7AreaDB = 0x84;
public const byte S7AreaCT = 0x1C;
public const byte S7AreaTM = 0x1D;
// Word Length
public const int S7WLBit = 0x01;
public const int S7WLByte = 0x02;
public const int S7WLChar = 0x03;
public const int S7WLWord = 0x04;
public const int S7WLInt = 0x05;
public const int S7WLDWord = 0x06;
public const int S7WLDInt = 0x07;
public const int S7WLReal = 0x08;
public const int S7WLCounter = 0x1C;
public const int S7WLTimer = 0x1D;
// PLC Status
public const int S7CpuStatusUnknown = 0x00;
public const int S7CpuStatusRun = 0x08;
public const int S7CpuStatusStop = 0x04;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct S7Tag
{
public Int32 Area;
public Int32 DBNumber;
public Int32 Start;
public Int32 Elements;
public Int32 WordLen;
}
#endregion
}
public class S7Timer
{
#region S7Timer
TimeSpan pt;
TimeSpan et;
bool input = false;
bool q = false;
public S7Timer(byte[] buff, int position)
{
if (position + 12 < buff.Length)
{
return;
}
else
{
SetTimer(new List<byte>(buff).GetRange(position, 16).ToArray());
}
}
public S7Timer(byte[] buff)
{
SetTimer(buff);
}
private void SetTimer(byte[] buff)
{
if (buff.Length != 12)
{
this.pt = new TimeSpan(0);
this.et = new TimeSpan(0);
}
else
{
Int32 resPT;
resPT = buff[0]; resPT <<= 8;
resPT += buff[1]; resPT <<= 8;
resPT += buff[2]; resPT <<= 8;
resPT += buff[3];
this.pt = new TimeSpan(0, 0, 0, 0, resPT);
Int32 resET;
resET = buff[4]; resET <<= 8;
resET += buff[5]; resET <<= 8;
resET += buff[6]; resET <<= 8;
resET += buff[7];
this.et = new TimeSpan(0, 0, 0, 0, resET);
this.input = (buff[8] & 0x01) == 0x01;
this.q = (buff[8] & 0x02) == 0x02;
}
}
public TimeSpan PT
{
get
{
return pt;
}
}
public TimeSpan ET
{
get
{
return et;
}
}
public bool IN
{
get
{
return input;
}
}
public bool Q
{
get
{
return q;
}
}
#endregion
}
public static class S7
{
#region [Help Functions]
private static Int64 bias = 621355968000000000; // "decimicros" between 0001-01-01 00:00:00 and 1970-01-01 00:00:00
private static int BCDtoByte(byte B)
{
return ((B >> 4) * 10) + (B & 0x0F);
}
private static byte ByteToBCD(int Value)
{
return (byte)(((Value / 10) << 4) | (Value % 10));
}
private static byte[] CopyFrom(byte[] Buffer, int Pos, int Size)
{
byte[] Result = new byte[Size];
Array.Copy(Buffer, Pos, Result, 0, Size);
return Result;
}
public static int DataSizeByte(int WordLength)
{
switch (WordLength)
{
case S7Consts.S7WLBit: return 1; // S7 sends 1 byte per bit
case S7Consts.S7WLByte: return 1;
case S7Consts.S7WLChar: return 1;
case S7Consts.S7WLWord: return 2;
case S7Consts.S7WLDWord: return 4;
case S7Consts.S7WLInt: return 2;
case S7Consts.S7WLDInt: return 4;
case S7Consts.S7WLReal: return 4;
case S7Consts.S7WLCounter: return 2;
case S7Consts.S7WLTimer: return 2;
default: return 0;
}
}
#region Get/Set the bit at Pos.Bit
public static bool GetBitAt(byte[] Buffer, int Pos, int Bit)
{
byte[] Mask = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
if (Bit < 0) Bit = 0;
if (Bit > 7) Bit = 7;
return (Buffer[Pos] & Mask[Bit]) != 0;
}
public static void SetBitAt(ref byte[] Buffer, int Pos, int Bit, bool Value)
{
byte[] Mask = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
if (Bit < 0) Bit = 0;
if (Bit > 7) Bit = 7;
if (Value)
Buffer[Pos] = (byte)(Buffer[Pos] | Mask[Bit]);
else
Buffer[Pos] = (byte)(Buffer[Pos] & ~Mask[Bit]);
}
#endregion
#region Get/Set 8 bit signed value (S7 SInt) -128..127
public static int GetSIntAt(byte[] Buffer, int Pos)
{
int Value = Buffer[Pos];
if (Value < 128)
return Value;
else
return (int)(Value - 256);
}
public static void SetSIntAt(byte[] Buffer, int Pos, int Value)
{
if (Value < -128) Value = -128;
if (Value > 127) Value = 127;
Buffer[Pos] = (byte)Value;
}
#endregion
#region Get/Set 16 bit signed value (S7 int) -32768..32767
public static int GetIntAt(byte[] Buffer, int Pos)
{
return (short)((Buffer[Pos] << 8) | Buffer[Pos + 1]);
}
public static void SetIntAt(byte[] Buffer, int Pos, Int16 Value)
{
Buffer[Pos] = (byte)(Value >> 8);
Buffer[Pos + 1] = (byte)(Value & 0x00FF);
}
#endregion
#region Get/Set 32 bit signed value (S7 DInt) -2147483648..2147483647
public static int GetDIntAt(byte[] Buffer, int Pos)
{
int Result;
Result = Buffer[Pos]; Result <<= 8;
Result += Buffer[Pos + 1]; Result <<= 8;
Result += Buffer[Pos + 2]; Result <<= 8;
Result += Buffer[Pos + 3];
return Result;
}
public static void SetDIntAt(byte[] Buffer, int Pos, int Value)
{
Buffer[Pos + 3] = (byte)(Value & 0xFF);
Buffer[Pos + 2] = (byte)((Value >> 8) & 0xFF);
Buffer[Pos + 1] = (byte)((Value >> 16) & 0xFF);
Buffer[Pos] = (byte)((Value >> 24) & 0xFF);
}
#endregion
#region Get/Set 64 bit signed value (S7 LInt) -9223372036854775808..9223372036854775807
public static Int64 GetLIntAt(byte[] Buffer, int Pos)
{
Int64 Result;
Result = Buffer[Pos]; Result <<= 8;
Result += Buffer[Pos + 1]; Result <<= 8;
Result += Buffer[Pos + 2]; Result <<= 8;
Result += Buffer[Pos + 3]; Result <<= 8;
Result += Buffer[Pos + 4]; Result <<= 8;
Result += Buffer[Pos + 5]; Result <<= 8;
Result += Buffer[Pos + 6]; Result <<= 8;
Result += Buffer[Pos + 7];
return Result;
}
public static void SetLIntAt(byte[] Buffer, int Pos, Int64 Value)
{
Buffer[Pos + 7] = (byte)(Value & 0xFF);
Buffer[Pos + 6] = (byte)((Value >> 8) & 0xFF);
Buffer[Pos + 5] = (byte)((Value >> 16) & 0xFF);
Buffer[Pos + 4] = (byte)((Value >> 24) & 0xFF);
Buffer[Pos + 3] = (byte)((Value >> 32) & 0xFF);
Buffer[Pos + 2] = (byte)((Value >> 40) & 0xFF);
Buffer[Pos + 1] = (byte)((Value >> 48) & 0xFF);
Buffer[Pos] = (byte)((Value >> 56) & 0xFF);
}
#endregion
#region Get/Set 8 bit unsigned value (S7 USInt) 0..255
public static byte GetUSIntAt(byte[] Buffer, int Pos)
{
return Buffer[Pos];
}
public static void SetUSIntAt(byte[] Buffer, int Pos, byte Value)
{
Buffer[Pos] = Value;
}
#endregion
#region Get/Set 16 bit unsigned value (S7 UInt) 0..65535
public static UInt16 GetUIntAt(byte[] Buffer, int Pos)
{
return (UInt16)((Buffer[Pos] << 8) | Buffer[Pos + 1]);
}
public static void SetUIntAt(byte[] Buffer, int Pos, UInt16 Value)
{
Buffer[Pos] = (byte)(Value >> 8);
Buffer[Pos + 1] = (byte)(Value & 0x00FF);
}
#endregion
#region Get/Set 32 bit unsigned value (S7 UDInt) 0..4294967296
public static UInt32 GetUDIntAt(byte[] Buffer, int Pos)
{
UInt32 Result;
Result = Buffer[Pos]; Result <<= 8;
Result |= Buffer[Pos + 1]; Result <<= 8;
Result |= Buffer[Pos + 2]; Result <<= 8;
Result |= Buffer[Pos + 3];
return Result;
}
public static void SetUDIntAt(byte[] Buffer, int Pos, UInt32 Value)
{
Buffer[Pos + 3] = (byte)(Value & 0xFF);
Buffer[Pos + 2] = (byte)((Value >> 8) & 0xFF);
Buffer[Pos + 1] = (byte)((Value >> 16) & 0xFF);
Buffer[Pos] = (byte)((Value >> 24) & 0xFF);
}
#endregion
#region Get/Set 64 bit unsigned value (S7 ULint) 0..18446744073709551616
public static UInt64 GetULIntAt(byte[] Buffer, int Pos)
{
UInt64 Result;
Result = Buffer[Pos]; Result <<= 8;
Result |= Buffer[Pos + 1]; Result <<= 8;
Result |= Buffer[Pos + 2]; Result <<= 8;
Result |= Buffer[Pos + 3]; Result <<= 8;
Result |= Buffer[Pos + 4]; Result <<= 8;
Result |= Buffer[Pos + 5]; Result <<= 8;
Result |= Buffer[Pos + 6]; Result <<= 8;
Result |= Buffer[Pos + 7];
return Result;
}
public static void SetULintAt(byte[] Buffer, int Pos, UInt64 Value)
{
Buffer[Pos + 7] = (byte)(Value & 0xFF);
Buffer[Pos + 6] = (byte)((Value >> 8) & 0xFF);
Buffer[Pos + 5] = (byte)((Value >> 16) & 0xFF);
Buffer[Pos + 4] = (byte)((Value >> 24) & 0xFF);
Buffer[Pos + 3] = (byte)((Value >> 32) & 0xFF);
Buffer[Pos + 2] = (byte)((Value >> 40) & 0xFF);
Buffer[Pos + 1] = (byte)((Value >> 48) & 0xFF);
Buffer[Pos] = (byte)((Value >> 56) & 0xFF);
}
#endregion
#region Get/Set 8 bit word (S7 Byte) 16#00..16#FF
public static byte GetByteAt(byte[] Buffer, int Pos)
{
return Buffer[Pos];
}
public static void SetByteAt(byte[] Buffer, int Pos, byte Value)
{
Buffer[Pos] = Value;
}
#endregion
#region Get/Set 16 bit word (S7 Word) 16#0000..16#FFFF
public static UInt16 GetWordAt(byte[] Buffer, int Pos)
{
return GetUIntAt(Buffer, Pos);
}
public static void SetWordAt(byte[] Buffer, int Pos, UInt16 Value)
{
SetUIntAt(Buffer, Pos, Value);
}
#endregion
#region Get/Set 32 bit word (S7 DWord) 16#00000000..16#FFFFFFFF
public static UInt32 GetDWordAt(byte[] Buffer, int Pos)
{
return GetUDIntAt(Buffer, Pos);
}
public static void SetDWordAt(byte[] Buffer, int Pos, UInt32 Value)
{
SetUDIntAt(Buffer, Pos, Value);
}
#endregion
#region Get/Set 64 bit word (S7 LWord) 16#0000000000000000..16#FFFFFFFFFFFFFFFF
public static UInt64 GetLWordAt(byte[] Buffer, int Pos)
{
return GetULIntAt(Buffer, Pos);
}
public static void SetLWordAt(byte[] Buffer, int Pos, UInt64 Value)
{
SetULintAt(Buffer, Pos, Value);
}
#endregion
#region Get/Set 32 bit floating point number (S7 Real) (Range of Single)
public static Single GetRealAt(byte[] Buffer, int Pos)
{
UInt32 Value = GetUDIntAt(Buffer, Pos);
byte[] bytes = BitConverter.GetBytes(Value);
return BitConverter.ToSingle(bytes, 0);
}
public static void SetRealAt(byte[] Buffer, int Pos, Single Value)
{
byte[] FloatArray = BitConverter.GetBytes(Value);
Buffer[Pos] = FloatArray[3];
Buffer[Pos + 1] = FloatArray[2];
Buffer[Pos + 2] = FloatArray[1];
Buffer[Pos + 3] = FloatArray[0];
}
#endregion
#region Get/Set 64 bit floating point number (S7 LReal) (Range of Double)
public static Double GetLRealAt(byte[] Buffer, int Pos)
{
UInt64 Value = GetULIntAt(Buffer, Pos);
byte[] bytes = BitConverter.GetBytes(Value);
return BitConverter.ToDouble(bytes, 0);
}
public static void SetLRealAt(byte[] Buffer, int Pos, Double Value)
{
byte[] FloatArray = BitConverter.GetBytes(Value);