Application Description S7 Db to Db Read/write

Project overview ��

Sharp7 is the C# port of Snap7 Customer. It�s non a wrapper, i.e. y'all don�t take an interface code that loads snap7.dll (or .then) but it�south a pure C# implementation of the S7Protocol.

Sharp7 is deployed as a single source file that contains some classes that y'all tin use directly in your .NET project to communicate with S7 PLCs.

Information technology�s designed to piece of work with small hardware .NET-based or fifty-fifty for big projects which don�t needs of extended command functions.

Master features

Fully standard �safe managed� C# code without whatsoever dependencies.

Virtually every hardware with an Ethernet adapter able to run a .Cyberspace Core can be continued to an S7 PLC.

Packed protocol headers to ameliorate performances.

Helper class to access to all S7 types without worrying near Little-Big endian conversion.

Uniform with Universal Windows Platform including Win10 IoT for Raspberry.

One single file.

Compatible with Snap7.net.cs, plug and play replaceable.

No additional libraries to deploy.

Licensing

Sharp7 is distributed as a source code library under GNU Library or Bottom General Public License version 3.0 (LGPLv3) .

Basically this means that you tin distribute your commercial firmware containing Sharp7 without the requirement to distribute the source lawmaking of your application and without the requirement that your firmware be itself distributed nether LGPL. A minor mention is all the same appreciated if you include it in your applications.

Disclaimer of Warranty

THERE IS NO WARRANTY FOR THE Programme, TO THE EXTENT PERMITTED BY APPLICABLE Law. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE Plan "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, But NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND Fitness FOR A PARTICULAR PURPOSE. THE Entire Run a risk AS TO THE QUALITY AND Operation OF THE Program IS WITH You. SHOULD THE PROGRAM Testify Lacking, Y'all Assume THE Toll OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

IF ANYONE BELIEVES THAT, WITH SHARP7 PROJECT HAVE BEEN VIOLATED SOME COPYRIGHTS, PLEASE EMAIL US, AND ALL THE NECESSARY CHANGES Volition BE Fabricated.

Sharp7 deploy

Sharp7 is a single file classes library.

For C# users : just add it in your C# project.

For VB users refer to the instance, you lot need to create the associates Sharp7.internet

S7Client reference

Authoritative functions

These methods allow decision-making the behavior a Client Object.

Function

Purpose

ConnectTo

Connects a Client Object to a PLC.

SetConnectionType

Sets the connexion type (PG/OP/S7Basic)

SetConnectionParams

Sets Address, Local and Remote TSAP for the connection.

Connect

Connects a Client Object to a PLC with implicit parameters.

Disconnect

Disconnects a Client.

SetConnectionType

Description

Sets the connection resources blazon, i.e. the way in which the Clients connects to a PLC.

Declaration

public void SetConnectionType( short ConnectionType )

Parameters

Type

Dir.

ConnectionType

short

In

See the tabular array

Connexion type table

Connection Type

Value

Helper Const

PG

0x01

S7.PG

OP

0x02

S7.OP

S7 Basic

0x03..0x10

S7.S7_BASIC

ConnectTo

Description

Connects the client to the hardware at (IP, Rack, Slot) Coordinates.

Declaration

public int ConnectTo( String Address, int Rack, int Slot)

Parameters

Blazon

Dir.

Address

String

In

PLC/Equipment IPV4 Address
ex. �192.168.i.12�

Rack

int

In

PLC Rack number (run across below)

Slot

int

In

PLC Slot number (come across below)

Return value

0 : The Customer is successfully connected (or was already continued).

Other values : see the Errors Code List.

Rack and Slot

In addition to the IP Address, that we all understand, there are two other parameters that index the unit : Rack (0..seven) and Slot (one..31) that you lot detect into the hardware configuration of your projection, for a physical component, or into the Station Configuration manager for WinAC.

At that place is however some special cases for which those values ​​ are stock-still or can work with a default as you tin can run into in the next tabular array.

Rack

Slot

S7 300 CPU

0

2

E'er

S7 400 CPU

Non fixed

Follow the hardware configuration.

WinAC CPU

Not fixed

Follow the hardware configuration.

S7 1200 CPU

0

0

Or 0, ane

S7 1500 CPU

0

0

Or 0, ane

WinAC IE

0

0

Or follow Hardware configuration.

Let�s see some examples of hardware configuration:

rack

S7 400 Rack

Rack

Slot

CPU 1

0

iv

CPU 2

0

11

The same concept for WinAC CPU which index can vary within the PC Station Rack.

rack300

S7300 Rack

S7300 CPU is ever present in Rack 0 at Slot ii

SetConnectionParams

Description

Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates.

Declaration

public void SetConnectionParams( Cord Address, int LocalTSAP,
int RemoteTSAP)

Parameters

Type

Dir.

Address

String

In

PLC/Equipment IPV4 Address
ex. �192.168.1.12�

LocalTSAP

int

In

Local TSAP (PC TSAP)

RemoteTSAP

int

In

Remote TSAP (PLC TSAP)

Remarks

This role must be called merely before Connect().

Connect

Description

Connects the client to the PLC with the parameters specified in the previous call of ConnectTo () or SetConnectionParams().

Annunciation

public int Connect()

Render value

0 : The Customer is successfully connected (or was already continued).

Other values : see the Errors Code List.

Remarks

This function tin be called only after a previous of ConnectTo () or SetConnectionParams() which internally sets Address and TSAPs.

Disconnect

Description

Disconnects �gracefully� the Customer from the PLC .

Declaration

public void Disconnect()

Remarks

This function can be called safely multiple times.

Subsequently calling this function LastError = 0 and Connected = false.

Base of operations Information I/O functions

These functions let the Client to exchange data with a PLC.

Part

Purpose

ReadArea

Reads a data surface area from a PLC.

WriteArea

Writes a data area into a PLC.

ReadMultiVars

Reads unlike kind of variables from a PLC simultaneously.

WriteMultiVars

Writes different kind of variables into a PLC simultaneously.

ReadArea

Description

This is the main function to read data from a PLC.
With it yous can read DB, Inputs, Outputs, Merkers, Timers and Counters.

Declaration

public int ReadArea( int Area, int DBNumber, int Start, int Amount, int WordLen, byte [] Buffer)

public int ReadArea( int Expanse, int DBNumber, int Showtime, int Amount, int WordLen, byte [] Buffer, ref int BytesRead)

Parameters

Type

Dir.

Mean

Surface area

int

In

Area identifier.

DBNumber

int

In

DB Number if  Expanse = S7AreaDB, otherwise is ignored.

Get-go

int

In

Starting time to outset

Amount

int

In

Amount of elements to read (i)

Wordlen

int

In

Word size (2)

Buffer

Byte Buffer

In

Buffer

BytesRead

int

Out

Number of bytes read (iii)

(one) Notation the apply of the parameter name �amount�, it means quantity of elements, non byte size.

Area table

Value

Mean

S7Consts.S7AreaPE

0x81

Procedure Inputs.

S7Consts.S7AreaPA

0x82

Procedure Outputs.

S7Consts.S7AreaMK

0x83

Merkers .

S7Consts.S7AreaDB

0x84

DB

S7Consts.S7AreaCT

0x1C

Counters.

S7Consts.S7AreaTM

0x1D

Timers

WordLen table

Value

Mean

S7WLBit

0x01

Bit (inside a discussion)

S7WLByte

0x02

Byte (eight bit)

S7WLWord

0x04

Discussion (xvi scrap)

S7WLDWord

0x06

Double Give-and-take (32 bit)

S7WLReal

0x08

Existent (32 fleck float)

S7WLCounter

0x1C

Counter (16 bit)

S7WLTimer

0x1D

Timer (16 bit)

Render value

0 : The role was achieved with no errors.

Other values : see the Errors Code List.

Remarks

As said, every data package exchanged with a PLC must fit in a PDU, whose size is fixed and varies from 240 up to 960 bytes.

This part completely hides this concept, the data that you lot tin can transfer in a single call depends only on the size bachelor of the data area (i.e. patently, yous cannot read 1024 bytes from a DB whose size is 300 bytes).

If this information size exceeds the PDU size, the package is automatically carve up beyond more subsequent transfers.

If either S7AreaCT or S7AreaTM is selected, WordLen must be either S7WLCounter or S7WLTimer (Even so no error is raised and the values are internally fixed).

Your buffer should exist big enough to receive the data.

Peculiarly:

Buffer size (byte) = Word size * Amount

Where:

Word size

S7Consts.S7WLBit

i

S7Consts.S7WLByte

one

S7Consts.S7WLWord

2

S7Consts.S7WLDWord

4

S7Consts.S7WLReal

four

S7Consts.S7WLCounter

ii

S7Consts.S7WLTimer

2

Notes

(ii) When WordLen =S7WLBit the Offset (Starting time) must be expressed in $.25.
Ex. The Start for DB4.DBX 10.3 is (ten*8)+iii = 83.

(iii) Since Corporeality is the number of elements read, BytesRead returns the constructive number of bytes.

WriteArea

Description

This is the main role to write data into a PLC. Information technology�s the complementary function of ReadArea(), the parameters and their meanings are the same.

The only difference is that the data is transferred from the byte buffer into PLC.

Declaration

public int WriteArea( int Area, int DBNumber, int Start, int Amount, int WordLen, byte [] Buffer)

public int WriteArea( int Area, int DBNumber, int First, int Amount, int WordLen, byte [] Buffer, ref int BytesWritten)

Run across ReadArea () for parameters and remarks.

Use S7 helper methods to insert S7 information types (int, word, real �) into the byte buffer.

ReadMultiVars

Description

This is part allows to read different kind of variables from a PLC in a single call.
With it you tin read DB, Inputs, Outputs, Merkers, Timers and Counters.

Annunciation

public int ReadMultiVars( S7DataItem [] Items, int ItemsCount)

Parameters

Blazon

Dir.

Item

S7DataItem[]

In

Run into below

ItemsCount

integer

In

Number of Items to read.

S7DataItem struct

Type

Dir.

Area

int

In

Area identifier.

Wordlen

int

In

Word size

Outcome

int

Out

Detail performance result (2)

DBNumber

int

In

DB Number if  Area = S7AreaDB, otherwise is ignored.

Start

int

In

First to start

Amount

int

In

Amount of words to read (1)

pData

IntPtr

In

Pointer to user Buffer

(1) Note the utilise of the parameter proper name �amount�, information technology means quantity of words, non byte size.

Render value

0 : The role was accomplished with no errors.

Other values : see the Errors Code List.

(2)  Since could happen that some variables are read, some other not because peradventure they don't exist in PLC. Is important to check the single particular Effect.

Remarks

To use ReadMultiVars a special class is supplied S7MultiVar that avoids the use of dangerous code (since there is a IntPtr)

Due the different kind of variables involved , there is no split characteristic available for this function, so the maximum information size must not exceed the PDU size.

The advantage of this function becomes big when you accept many small noncontiguous variables to be read.

WriteMultiVars

Description

This is office allows to write unlike kind of variables from a PLC in a single call.
With it you tin read DB, Inputs, Outputs, Merkers, Timers and Counters.

Declaration

public int WriteMultiVars( S7DataItem [] Items, int ItemsCount)

Parameters

Type

Dir.

Particular

S7DataItem[]

In

Meet beneath

ItemsCount

integer

In

Number of Items to write.

S7DataItem struct

Type

Dir.

Surface area

int

In

Area identifier.

Wordlen

int

In

Word size

Effect

int

Out

Item operation result (2)

DBNumber

int

In

DB Number if  Area = S7AreaDB, otherwise is ignored.

Showtime

int

In

Showtime to get-go

Corporeality

int

In

Amount of words to write (1)

pData

IntPtr

In

Pointer to user Buffer

(two) Note the utilize of the parameter name �corporeality�, it means quantity of words, not byte size.

Return value

0 : The office was achieved with no errors.

Other values : see the Errors Code List.

(2)  Since could happen that some variables are written, some other not because peradventure they don't exist in PLC. Is important to check the single item Result.

Remarks

To apply WriteMultiVars a special form is supplied S7MultiVar that avoids the employ of unsafe code (since there is a IntPtr)

Due the different kind of variables involved , there is no split feature bachelor for this function, so the maximum data size must non exceed the PDU size

The advantage of this role becomes big when you lot have many small noncontiguous variables to be written.

Lean Information I/O functions

These are utility functions that simplify the use of ReadArea and WriteArea.

I.due east. they call internally ReadArea and WriteArea passing the correct Expanse and WordLen .

Function

Purpose

DBRead

Reads a part of a DB from a PLC.

DBWrite

Writes a part of a DB into a PLC.

ABRead

Reads a office of IPU area from a PLC.

ABWrite

Writes a part of IPU area into a PLC.

EBRead

Reads a part of IPI area from a PLC.

EBWrite

Writes a office of IPI expanse into a PLC.

MBRead

Reads a part of Merkers area from a PLC.

MBWrite

Writes a part of Merkers surface area into a PLC.

TMRead

Reads timers from a PLC.

TMWrite

Write timers into a PLC.

CTRead

Reads counters from a PLC.

CTWrite

Write counters into a PLC.

Block oriented functions

Role

Purpose

GetAgBlockInfo

Returns info virtually a given block in PLC memory.

DBGet

Uploads a DB from the PLC

DBFill

Fills a DB into the PLC with a given value.

GetAgBlockInfo

Description

Returns some information near a given block.
This function is very useful if you need to read or write data in a DB which you do not know the size in advance (come across MC7Size field).

This function is used internally by DBGet.

Annunciation

public int GetAgBlockInfo( int BlockType, int BlockNumber,

ref S7BlockInfo Block)

Parameters

Type

Dir.

BlockType

int

In

Type of Block that nosotros need

BlockNum

int

In

Number of Cake

Block

S7BlockInfo

in

S7BlockInfo struct

BlockType values

Helper Const

Type

Value

S7Consts.Block_OB

OB

0x38

S7 Consts.Block_DB

DB

0x41

S7 Consts.Block_SDB

SDB

0x42

S7 Consts.Block_FC

FC

0x43

S7 Consts.Block_SFC

SFC

0x44

S7 Consts.Block_FB

FB

0x45

S7 Consts.Block_SFB

SFB

0x46

S7BlockInfo struct

public struct S7BlockInfo {

public int BlkType;    // Block Type (meet SubBlkType table)

public int BlkNumber;  // Block number

public int BlkLang;    // Cake Linguistic communication (see LangType Table)

public int BlkFlags;   // Block flags (bitmapped)

public int MC7Size;    // The real size in bytes

public int LoadSize;   // Load retentivity size

public int LocalData;  // Local data

public int SBBLength;  // SBB Length

public int CheckSum;   // Checksum

public int Version;    // Version (BCD 00<HI><LO>)

public string ;         // Code date

public string; // Interface engagement

public string;   // Author

public string;         // Family

public cord;         // Header

};

This struct is filled by the office, some fields require additional info:

SubBlockType table

Value

Blazon

SubBlk_OB

0x08

OB

SubBlk_DB

0x0A

DB

SubBlk_SDB

0x0B

SDB

SubBlk_FC

0x0C

FC

SubBlk_SFC

0x0D

SFC

SubBlk_FB

0x0E

FB

SubBlk_SFB

0x0F

SFB

LangType table

Value

Block Language

BlockLangAWL

0x01

AWL

BlockLangKOP

0x02

KOP

BlockLangFUP

0x03

FUP

BlockLangSCL

0x04

SCL

BlockLangDB

0x05

DB

BlockLangGRAPH

0x06

GRAPH

Return value

0 : The function was accomplished with no errors.

Other values : see the Errors Code List.

DBGet

Description

Read an entire DB from the PLC without the need of specifying its size. As output SizeRead volition contain the size read.

This function is not field of study to the security level prepare.

Declaration

public int DBGet( int DBNumber, byte[] usrData, ref int Size)

Parameters

Type

Dir.

DBNumber

int

In

DB Number

Data

byte array

in

Address of the user buffer

SizeRead

int ref

In/Out

In : Buffer size supplied

Out : Number of bytes read

Return value

0 : The office was accomplished with no errors.

Other values : see the Errors Code List.

Remarks

This function first gathers the DB size via GetAgBlockInfo then calls ReadArea if the Buffer size is greater than the DB size, otherwise returns an fault.

DBFill

Description

Fills a DB in AG with a given byte without the need of specifying its size.

Declaration

public int Cli_DBFill( int DBNumber, int FillChar );

Parameters

Blazon

Dir.

DBNumber

integer 32

In

DB Number

FillChar

Integer 32

in

Byte pattern

Return value

0 : The function was achieved with no errors.

Other values : see the Errors Code List.

Remarks

Fillchar is an integer for efficiency reasons, only the lowest byte is used.

Date/Time functions

These functions permit to read/modify the date and time of a PLC.

Imagine a product line in which each PLC saves the data with date/time field within, information technology is very important that the date be upwards to engagement.

Both CP X43 and internal PN allow to synchronize appointment and fourth dimension just you need an NTP server, and in some cases (sometime hardware or CP343-one Lean or former firmware release) this doesn�t piece of work properly.

Snap7 Client, using the same method of S7 Managing director, always works.

Function

Purpose

GetPlcDateTime

Returns the PLC date/time.

SetPlcDateTime

Sets the PLC date/time with a given value.

SetPlcSystemDateTime

Sets the PLC engagement/time with the host (PC) date/time.

GetPlcDateTime

Description

Reads PLC date and time into a C# DateTime class instance.

Declaration

public int GetPlcDateTime ( ref DateTime DT)

Parameters

Blazon

Dir.

DateTime

Date

In

DateTime grade instance

Return value

0 : The function was accomplished with no errors.

Other values : see the Errors Lawmaking Listing.

SetPlcDateTime

Description

Sets the PLC date and time.

Declaration

public int SetPlcDateTime ( DateTime DT)

Parameters

Type

Dir.

DateTime

Date

In

DateTime grade case

Render value

0 : The function was accomplished with no errors.

Other values : come across the Errors Code List.

SetPlcSystemDateTime

Clarification

Sets the PLC appointment and time in accord to the PC system Date/Time.

Declaration

public int SetPlcSystemDateTime ()

Return value

0 : The part was accomplished with no errors.

Other values : meet the Errors Code List.

Organization info functions

these functions admission to SZL (or SSL - System Status List) to give yous nonetheless information that yous can get from S7 Manager.

Organisation Status List

The system condition listing (SSL) describes the current status of a programmable logic controller.

The contents of the SSL can simply be read using data functions but cannot exist modified. The fractional lists are virtual lists, in other words, they are just created by the operating system of the CPUs when specifically requested.

You can admission to arrangement condition list using SFC 51 likewise "RDSYSST."

To read a partial list you lot must specify its ID and Index.

For a detailed description of SZL see:

�33 of "Organisation Software for S7-300/400 Organization and Standard Functions" .

Function

Purpose

ReadSZL

Reads a partial listing of given ID and Index.

GetOrderCode

Returns the CPU order code.

GetCpuInfo

Returns some information nigh the AG.

GetCpInfo

Returns some information about the CP (advice processor).

ReadSZL

Description

Reads a fractional list of given ID and Index.

Annunciation

public int ReadSZL( int ID, int Index, ref S7SZL SZL, ref int Size)

Parameters

Blazon

Dir.

ID

int

In

List ID

Index

int

In

Listing Alphabetize

SZL

S7Szl

in

S7Szl class instance

Size

int

out

Size Read in bytes

S7SZL

[ StructLayout ( LayoutKind .Sequential , Pack = i)]

 public struct SZL_HEADER

 {

public UInt16 LENTHDR;

public UInt16 N_DR;

 };

 [ StructLayout ( LayoutKind .Sequential , Pack = ane)]

public struct S7SZL

 {

public SZL_HEADER Header;

     [ MarshalAs ( UnmanagedType .ByValArray )]

public byte [] Data;

 };

Type

Dir.

Hateful

LENTHDR

integer

Out

Length of a data tape of the partial list in bytes

N_DR

integer

Out

Number of data records independent in the partial list.

Return value

0 : The function was achieved with no errors.

Other values : see the Errors Code List.

Remarks

Retrieve to allocate the Data[] buffer (see the demo)

GetOrderCode

Clarification

Gets CPU order code and version info.

Declaration

public int GetOrderCode( S7OrderCode Info)

Parameters

Type

Dir.

Info

S7OrderCode

Out

See below

public struct S7OrderCode

{

public string Code;

public byte V1; // Version 1st digit

public byte V2; // Version 2d digit

public byte V3; // Version 3th digit

};

The Gild code is a string such as �6ES7 151-8AB01-0AB0�

GetCpuInfo

Description

Gets CPU module name, serial number and other info.

Proclamation

public int GetCpuInfo( S7CpuInfo Info)

Parameters

Type

Dir.

Info

S7CpuInfo

Out

See beneath

public struct S7CpuInfo

{

public string ModuleTypeName;

public cord SerialNumber;

public string ASName;

public cord Copyright;

public cord ModuleName;

}

Return value

0 : The function was achieved with no errors.

Other values : see the Errors Code List.

GetCpInfo

Description

Gets CP (communication processor) info.

Declaration

public int GetCpInfo( S7CpInfo Info)

Parameters

Blazon

Dir.

Info

S7CpInfo

Out

See beneath

S7CpInfo

public struct S7CpInfo

{

public int MaxPduLength;

public int MaxConnections;

public int MaxMpiRate;

public int MaxBusRate;

};

Render value

0 : The function was achieved with no errors.

Other values : meet the Errors Code Listing.

PLC command functions

With these control part it�s possible to Start/Stop a CPU and read the PLC status.

Function

Purpose

PlcColdStart

Puts the CPU in RUN mode performing an COLD Commencement.

PlcHotStart

Puts the CPU in RUN mode performing an HOT Outset.

PlcStop

Puts the CPU in Cease mode.

PlcGetStatus

Returns the CPU status (running/stopped).

PlcColdStart

Description

Puts the CPU in RUN fashion performing an COLD START.

Declaration

public int PlcColdStart()

Render value

0 : The function was achieved with no errors.

Other values : Either the PLC is already running or the current protection level is non met to perform this operation.

Remarks

This function is subject to the security level set.

PlcHotStart

Description

Puts the CPU in RUN manner performing an HOT Start.

Announcement

public int PlcHotStart()

Render value

0 : The part was accomplished with no errors.

Other values : Either the PLC is already running or the current protection level is not met to perform this operation.

Remarks

This part is bailiwick to the security level gear up.

PlcStop

Description

Puts the CPU in Finish mode.

Announcement

public int PlcStop ()

Return value

0 : The function was accomplished with no errors.

Other values : Either the PLC is already stopped or the electric current protection level is non met to perform this operation.

Remarks

This function is subject to the security level set up.

PlcGetStatus

Description

Returns the CPU condition (running/stopped) into Status.Value .

Annunciation

public int GetPlcStatus( ref int Status)

Parameters

Type

Dir.

Status

int

Out

Plc status

Condition values

Helper Const

Value

S7.S7CpuStatusUnknown

0x00

The CPU status is unknown.

S7.S7CpuStatusRun

0x08

The CPU is running.

S7.S7CpuStatusStop

0x04

The CPU is stopped.

Render value

0 : The office was accomplished with no errors.

Other values : come across the Errors Code List.

Security functions

With these functions is possible to know the current protection level, and to fix/clear the current session password.

The right proper name of the below functions SetSessionPassword and ClearSessionPassword, would accept to be Login and Logout to avert misunderstandings about their scope.

Specially because, if you look at the source code, at that place is an encoding function that translates the obviously password before transport it to the PLC.

Password HACKING IS VERY FAR FROM THE AIM OF THIS Project, MOREOVER YOU NEED TO KNOW THE Correct PASSWORD TO Come across THE CPU SECURITY LEVEL .

Detailed data about the protection level can exist found in �33.nineteen of "System Software for S7-300/400 System and Standard Functions" .

Office

Purpose

SetSessionPassword

Transport the password to the PLC to meet its security level.

ClearSessionPassword

Clears the password set for the current session (logout).

GetProtection

Gets the CPU protection level info.

SetSessionPassword

Clarification

Send the password to the PLC to meet its security level.

Proclamation

public int SetSessionPassword( string Password);

Parameters

Blazon

Dir.

Countersign

String

In

8 chars UTF-viii string

Return value

0 : The role was accomplished with no errors.

Other values : see the Errors Code List.

Remarks

A password accepted by a PLC is an eight chars string, a greater password volition be truncated, and a smaller one will be "right infinite padded".

ClearSessionPassword

Clarification

Clears the password set for the current session (logout).

Announcement

public int ClearSessionPassword()

Return value

0 : The function was accomplished with no errors.

Other values : see the Errors Lawmaking Listing.

GetProtection

Description

Gets the CPU protection level info.

Declaration

public int GetProtection(ref S7Protection Protection)

Parameters

Type

Dir.

Protection

S7Protection

Out

See below

TS7Protection fields

public struct S7Protection

{

public ushort sch_schal;

public ushort sch_par;

public ushort sch_rel;

public ushort bart_sch;

public ushort anl_sch;

};

Field Values

Values

sch_schal

1, 2, 3

Protection level set with the manner selector.

sch_par

0, 1, 2, 3

Password level, 0 : no password

sch_rel

0, i, two, iii

Valid protection level of the CPU

bart_sch

1, ii, 3, 4

Mode selector setting (one:RUN, ii:RUN-P, 3:Finish, 4:MRES, 0:undefined or cannot be adamant)

anl_sch ;

0, 1, ii

Startup switch setting (i:CRST, 2:WRST, 0:undefined, does

not exist of cannot exist determined)

Encounter also �33.nineteen of "System Software for S7-300/400 Organization and Standard Functions"

Return value

0 : The office was accomplished with no errors.

Other values : see the Errors Code List.

Properties/Info Functions

ConnTimeout

int , in/Out � Gets/Sets the connection timeout (in milliseconds) for a telegram.

RecvTimeout

int , in/out � Gets/Sets the receiving timeout (in milliseconds) for a telegram.

SendTimeout

int , in/out � Gets/Sets the sending timeout (in milliseconds) for a telegram.

Connected

bool , out � It�s true if the Client is connected.

PduSizeNegotiated

int , out � Returns the PDU size negotiated.

PduSizeRequested

int , in/out � Gets/Sets the PDU size to be negotiated.

PLCPort

int , in/out � Gets/Sets the connection Port (by default is 102).

ExecutionTime

int , out � Returns the concluding performance execution fourth dimension in ms.

public int LastError ()

Returns the last operation error.

public cord ErrorText( int Fault)

Returns a textual explanation of Error

public int ExecTime ()

Returns the last functioning execution time in ms. (compatibility with Snap7.internet.cs)

S7 Helper reference

This grade allow to read/write an �S7� value into a byte buffer, all new S71200/1500 types are supported.

Read functions are in format:

public static <.NET native Type> Get <S7 Type> At( byte[] Buffer, int Pos)

They excerpt a <S7 Type> var from the byte buffer starting from the byte number �pos�.

Write functions are in format:

public static void Set <S7 Type> At( byte[] Buffer, int Pos, <.NET native Type> Value)

They insert a .net native type var into the byte buffer starting from the byte number �pos�.

Data admission example

Now, but a real example of how to read a S7 struct from a PLC into .Cyberspace struct using this class in C# and VB .

Let�s suppose that we brand a leak test on an automotive component and that we want to acquire the result of this test.

The information of this test consists of some values (Component series number, Leak Value etc..) stored in DB 100 equally in figure.

Every time a component is tested this struct is filled by the PLC and we want to read information technology into a .NET struct, picking the fields and adjusting their byte-gild (the PLC is Large-Endian, the PC is Little-Endian, and so the bytes must exist reversed).

This is our C# sample struct:

public struct ComponentResult

{

public String SerialNumber; // Component Series Number

public int TestResult; // Result code 0:Unknown, i:Adept, 2:Fleck

public double LeakDetected; // Leak value [cc/min]

public DateTime TestDateTime; // Examination Timestamp

}

And this is the C# sample office that fills the struct. Notice that the outcome of whatsoever Client function call should be checked, hither is skipped for brevity.

individual ComponentResult LeakResult()

{

ComponentResult Upshot = new ComponentResult ();

byte [] Buffer = new byte [26];

// Reads the buffer.

Client.DBRead(100, 0, 26, Buffer);

// Extracts the fields and inserts them into the struct

Result.SerialNumber = S7 .GetCharsAt(Buffer, 0, 12);

Result.TestResult = S7 .GetIntAt(Buffer, 12);

Issue.LeakDetected = S7 .GetRealAt(Buffer, 14);

Result.TestDateTime = S7 .GetDateTimeAt(Buffer, 18);

return Outcome;

}

Same as to a higher place in VB.Internet

The struct

Private Construction ComponentResult

Public SerialNumber As Cord ' Component Serial Number

Public TestResult Equally Integer ' Upshot code 0:Unknown, one:Adept, 2:Scrap

Public LeakDetected Equally Double ' Leak value [cc/min]

Public TestDateTime As DateTime ' Test Timestamp

End Structure

�and the function

Individual Function LeakResult() Every bit ComponentResult

Dim Result As ComponentResult

Dim Buffer(26) As Byte

Client.DBRead(100, 0, 26, Buffer)

Outcome.SerialNumber = S7 .GetCharsAt(Buffer, 0, 12)

Result.TestResult = S7 .GetIntAt(Buffer, 12)

Result.LeakDetected = S7 .GetRealAt(Buffer, xiv)

Result.TestDateTime = S7 .GetDateTimeAt(Buffer, 18)

Render Result

End Function

Finally, if you put a push button and four labels in the form of VB demo, with this simple code you lot can test the machinery.

Individual Sub Button1_Click(sender Every bit Object , east As EventArgs ) Handles Button1.Click

Dim CR As ComponentResult = LeakResult()

   Label1.Text = CR.SerialNumber ' It�s already a string

   Label2.Text = System.Convert.ToString(CR.TestResult)

   Label3.Text = Arrangement.Convert.ToString(CR.LeakDetected)

   Label4.Text = System.Convert.ToString(CR.TestDateTime)

End Sub

S7MultiVar reference

This class allows to make full the S7DataItem[] and performs a ReadMultivar or WriteMultivar without using unsafe code.

The best way to empathize the apply of this class is analyzing an instance.

The process is simple:

i. Instantiate the form.

2. Add together the vars reference (i.e. your buffer) specifying the kind of element that we want read or write.

three. Call Read or Write method.

Read instance

// Multi Reader Example specifying Client

S7MultiVar Reader = new S7MultiVar (Customer);

// Our buffers

byte [] DB_A = new byte [1024];

byte [] DB_B = new byte [1024];

byte [] DB_C = new byte [1024];

// Our DB number references

int DBNumber_A = 1; // DB1

int DBNumber_B = ane; // DB2

int DBNumber_C = 1; // DB3

// Add Items def. specifying 16 bytes to read starting from 0

Reader.Add ( S7Consts .S7AreaDB, S7Consts .S7WLByte, DBNumber_A, 0, 16, ref DB_A);

Reader.Add ( S7Consts .S7AreaDB, S7Consts .S7WLByte, DBNumber_B, 0, xvi, ref DB_B);

Reader.Add ( S7Consts .S7AreaDB, S7Consts .S7WLByte, DBNumber_C, 0, 16, ref DB_C);

// Performs the Read

int Result = Reader.Read();

If everything is ok into DB_A, DB_B, DB_C we volition find the first 16 bytes of DB1, DB2 and DB3.

Remarks

1. Reader.Effect [] will contain the single consequence of the items, it�s possible that some items were read and some other not.

2. The parameters of Add() are the same of Read/WriteArea, you tin read/write non only DB but besides Due east/A/MK/T/C and too bits.

Error codes

Delight refer to code of the function ErrorText() for the caption

errTCPSocketCreation          = 0x00000001;

errTCPConnectionTimeout       = 0x00000002;

errTCPConnectionFailed        = 0x00000003;

errTCPReceiveTimeout          = 0x00000004;

errTCPDataReceive             = 0x00000005;

errTCPSendTimeout             = 0x00000006;

errTCPDataSend                = 0x00000007;

errTCPConnectionReset         = 0x00000008;

errTCPNotConnected            = 0x00000009;

errTCPUnreachableHost         = 0x00002751;

errIsoConnect                 = 0x00010000;

errIsoInvalidPDU              = 0x00030000;

errIsoInvalidDataSize         = 0x00040000;

errCliNegotiatingPDU          = 0x00100000;

errCliInvalidParams           = 0x00200000;

errCliJobPending              = 0x00300000;

errCliTooManyItems            = 0x00400000;

errCliInvalidWordLen          = 0x00500000;

errCliPartialDataWritten      = 0x00600000;

errCliSizeOverPDU             = 0x00700000;

errCliInvalidPlcAnswer        = 0x00800000;

errCliAddressOutOfRange       = 0x00900000;

errCliInvalidTransportSize    = 0x00A00000;

errCliWriteDataSizeMismatch   = 0x00B00000;

errCliItemNotAvailable        = 0x00C00000;

errCliInvalidValue            = 0x00D00000;

errCliCannotStartPLC          = 0x00E00000;

errCliAlreadyRun              = 0x00F00000;

errCliCannotStopPLC           = 0x01000000;

errCliCannotCopyRamToRom      = 0x01100000;

errCliCannotCompress          = 0x01200000;

errCliAlreadyStop             = 0x01300000;

errCliFunNotAvailable         = 0x01400000;

errCliUploadSequenceFailed    = 0x01500000;

errCliInvalidDataSizeRecvd    = 0x01600000;

errCliInvalidBlockType        = 0x01700000;

errCliInvalidBlockNumber      = 0x01800000;

errCliInvalidBlockSize        = 0x01900000;

errCliNeedPassword            = 0x01D00000;

errCliInvalidPassword         = 0x01E00000;

errCliNoPasswordToSetOrClear = 0x01F00000;

errCliJobTimeout              = 0x02000000;

errCliPartialDataRead         = 0x02100000;

errCliBufferTooSmall          = 0x02200000;

errCliFunctionRefused         = 0x02300000;

errCliDestroying              = 0x02400000;

errCliInvalidParamNumber      = 0x02500000;

errCliCannotChangeParam       = 0x02600000;

errCliFunctionNotImplemented = 0x02700000;

Images

Demo WinForm C# Windows 7

Demo Universal Windows Platform C# Windows 10

humeforejusell74.blogspot.com

Source: http://snap7.sourceforge.net/sharp7.html

0 Response to "Application Description S7 Db to Db Read/write"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel