Get

  1. The function block is started by setting the variable bGetTelegram in the main program to TRUE.
  2. The rising edge is then used to send a GET request with the function block IotHttpRequest.
  3. Once the request is complete, an error handling routine is invoked. If both the function block itself and the HTTP status code are error-free, the JSON response can be parsed by the web server in the PLC program.
FUNCTION_BLOCK FB_TestHTTP_Get_Telegram
VAR_INPUT
    bSend               : BOOL;
    sMessage            : STRING(500);
END_VAR
VAR_IN_OUT
    fbClient            : FB_IotHttpClient;
END_VAR
VAR_OUTPUT
    bBusy               : BOOL;
    bError              : BOOL;
END_VAR
VAR
    fbRequest           : FB_IotHttpRequest;
    fbJson              : FB_JsonDomParser;
    nState              : UDINT;
    RisingEdge          : R_TRIG;
    
    bGetContentResult   : BOOL;
    sContent            : STRING(511);
    
    bGetJsonResult      : BOOL;
    jsonDoc             : SJsonValue;
    jsonVal             : SJsonValue;
    sResultValue        : STRING;
    
    nReqCount           : UDINT;    
    nResCount           : UDINT;
    nValidResCount      : UDINT;
    nErrCount           : UDINT;
    fbFormatString      : FB_FormatString;
    sBotApiKey          : STRING(500):='1106704362:AAExFeda7Jf9CojjI9whLEzPeE4KDlDzEnf';
    sChatId             : STRING(500):='1140427258';
    sConMessage         : STRING(500);
END_VAR
RisingEdge(CLK:= bSend );
fbFormatString(
    sFormat := '/bot%s/sendMessage?chat_id=%s&text=%s', 
    arg1    := F_STRING(sBotApiKey), 
    arg2    := F_STRING(sChatId), 
    arg3    := F_STRING(sMessage), 
    bError  => , 
    nErrId  => , 
    sOut    => sConMessage);

CASE nState OF
0:    
    IF RisingEdge.Q THEN 
        IF fbRequest.SendRequest(sUri:=sConMessage, fbClient:=fbClient, eRequestType:=ETcIotHttpRequestType.HTTP_Get, 0, 0, 0) THEN                
            nState:= 1;
            nReqCount:= nReqCount+1;
            bBusy:= TRUE;
            bError:= FALSE;
        END_IF                    
    END_IF
1:
    IF NOT fbRequest.bBusy THEN
        bError:= TRUE;
        IF NOT fbRequest.bError THEN                 
            bGetContentResult:= fbRequest.GetContent(pContent:= ADR(sContent), nContentSize:= SIZEOF(sContent), bSetNullTermination:= TRUE);
            IF fbRequest.nStatusCode >= 200 AND fbRequest.nStatusCode < 300 THEN
                bGetJsonResult:= FALSE;
                jsonDoc:= fbRequest.GetJsonDomContent(fbJson);
                IF jsonDoc <> 0 THEN
                    ; // do something with the response
                    nValidResCount:= nValidResCount+1;
                    bError:= FALSE;    
                END_IF                            
                nResCount:= nResCount+1;            
            END_IF
        END_IF
        nState:= 0;
        bBusy:= FALSE;
        IF bError THEN
            nErrCount:= nErrCount+1;
        END_IF
    END_IF      
END_CASE