Sample: SNMP Get request

This samples describes how a TwinCAT device can answer on a SNMP GET-request from SNMP manager. If a GET-Request arrived in the PLC, the requested information will be sent if the object id match.

Download: PLC Project

Variablen Declaration

PROGRAM MAIN
VAR
    GetSnmp:    FB_GetSnmp;
    iValue:     DINT;
    sValue:     T_MaxString;
    arrVarBind: ARRAY[0..1] OF ST_SNMP_VariableBinding;
    iState : INT := 0;
END_VAR

PLC Program

CASE iState OF
    0:(* Enable *)
        GetSnmp.bEnable := TRUE;
        IF GetSnmp.bEnabled THEN
            iState := 10;
        END_IF

    10:(* Wait for SNMP GET request *)
        GetSnmp.bReceive := TRUE;
        IF GetSnmp.bReceived THEN
            GetSnmp.bReceive := FALSE;
            iState := 20;
        END_IF

    20: (* Compare oid's *)
        
        (* TODO: Assign your own ObjectID (oid) of the management information base (MIB) *)
        IF GetSnmp.sRecObjectID = '1.3.6.1.2.1.1.5.0' THEN
            sValue := 'BECKHOFF_DEVICE';
            arrVarBind[0].iType := E_SNMP_OCTETSTRING;
            arrVarBind[0].iLength :=LEN(sValue);
            arrVarBind[0].pArrValue := ADR(sValue);
            arrVarBind[0].sOID := GetSnmp.sRecObjectID;
            GetSnmp.pArrVarBinding := ADR(arrVarBind);
            GetSnmp.nVarBindings := 1;
            GetSnmp.iError := 0;
            GetSnmp.bSendResponse := TRUE;
        ELSE
        (* The requested ObjectID  was not found *)
            GetSnmp.nVarBindings := 0;
            GetSnmp.iError := 2;
            GetSnmp.bSendResponse := TRUE;
        END_IF
        iState := 30;

    30: (* reset *)
        GetSnmp.bSendResponse := FALSE;
        GetSnmp.bSendTrap := FALSE;
        IF NOT GetSnmp.bBusy THEN
            iState := 10;
        END_IF
        IF GetSnmp.bError THEN
            GetSnmp.bEnable := FALSE;
            iState := 0;
        END_IF
END_CASE

GetSnmp(
    (* TODO: check community string *)
        sCommunity := 'public',
        iGenericTrapNumber:= E_SNMP_WarmStart,
    (* TODO: add device IP of TwinCAT device *)
        sLocalHostIp := '',
    (* use SNMP Port 163, if default port 161 is in use by OS *)
        sLocalHostPort := 163,
    (* TODO: ADD SNMP Manager IP *)
        sManagerIP := '',
    );

Requirements

Development environment

Target system type

PLC libraries to be linked

TwinCAT version 2.8.0 or higher

PC or CX (x86)

TcSnmp.lib ( TcpIp.Lib; Standard.Lib; TcBase.Lib; TcSystem.Lib are included automatically )

TwinCAT v2.10.0 Build >= 1301

CX (ARM)