Read PI point summary value from PI Web API with C#

Hello all,

I have a C# code which reads PI point average values with PI SDK API. I have no skills on Web API... how could I do it with PI Web API ? Thanks.

 

    private static void GetfromPI(DateTime starttime, DateTime endtime, string pi_tag, string pi_server, out int ierror)

    {

      ierror = 0;

 

      double value = new double();

 

      string tag = @"\\" + pi_server + @"\" + pi_tag;

      PISDK.PISDK uPISDK = new PISDK.PISDK();

      PISDK.PIPoint pipoint = uPISDK.GetPoint(tag);

 

      try

      {

        pipoint = uPISDK.GetPoint(tag);

        if (pipoint.PointType == PISDK.PointTypeConstants.pttypDigital)

        {

          PISDK.DigitalState digstate = pipoint.Data.ArcValue(starttime, PISDK.RetrievalTypeConstants.rtAuto).Value;

          value = digstate.Code;

        }

        else

        { value = pipoint.Data.Summary(starttime, endtime, PISDK.ArchiveSummaryTypeConstants.astAverage).Value; }

      }

      catch (Exception)

      {

        ierror = 3;

        return;

      }

  • Hi. Here's what ChatGPT recommends.

    Please note:

    1. The stream_id they talk about is the WebId, and you'll probably need to query for it first, then use the WebId in the actual query)
    2. You'll need to access the Stream controller, and the GetSummary action.

     

    To call the AVEVA PI WebAPI and request a summary for a stream in C#, you can use the `HttpClient` class to send an HTTP request. Below is an example that demonstrates how to achieve this.

     

    Example: Requesting a Summary in C#

     

    This example assumes you are using Basic Authentication. If your PI WebAPI uses another form of authentication (e.g., Kerberos), you'll need to modify the code accordingly.

     

    Step 1: Setup the C# Project

    Ensure you have a .NET environment set up. You can use this in a .NET Core Console Application or any other .NET project type.

     

    Step 2: Add Necessary Using Directives

    You will need the following namespaces:

    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    using Newtonsoft.Json.Linq;

    Make sure to install the `Newtonsoft.Json` package for handling JSON if you haven't already.

     

    Step 3: Implement the Summary Request

    Here is a full example:

    class Program
    {
      static async Task Main(string[] args)
      {
        // Replace with your PI WebAPI server and stream ID
        string piWebApiServer = "https://<piwebapi_server>";
        string streamId = "<stream_id>";
    
        // Replace with your PI WebAPI credentials
        string username = "your_username";
        string password = "your_password";
    
        // Define the URL for the summary request
        string url = $"{piWebApiServer}/piwebapi/streams/{streamId}/summary";
    
        // Create a new HttpClient handler and client
        var handler = new HttpClientHandler();
        handler.PreAuthenticate = true;
        handler.UseDefaultCredentials = false;
        handler.Credentials = new System.Net.NetworkCredential(username, password);
    
        using (HttpClient client = new HttpClient(handler))
        {
          // Add authentication headers
          var authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
          client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken);
    
          // Add parameters to the URL
          string queryParams = "?summaryType=Total;Average&startTime=*-1d&endTime=*";
    
          url += queryParams;
    
          // Send the GET request
          HttpResponseMessage response = await client.GetAsync(url);
    
          // Check if the request was successful
          if (response.IsSuccessStatusCode)
          {
            // Read the response content
            string responseData = await response.Content.ReadAsStringAsync();
    
            // Parse the JSON response
            JObject summaryData = JObject.Parse(responseData);
    
            // Output the summary data
            Console.WriteLine(summaryData.ToString());
          }
          else
          {
            Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
          }
        }
      }
    }

    Explanation of the Code:

     

    - URL and Query Parameters:

     - The URL is constructed using your PI WebAPI server address and the stream ID for the data you want to summarize.

     - Query parameters are appended to specify the type of summary (`Total`, `Average`), and the time range (e.g., `*-1d` for the last day).

     

    - Authentication:

     - Basic Authentication is used by encoding the username and password into a Base64 string. This is then passed as an `Authorization` header.

     

    - HttpClient Setup:

     - `HttpClient` is configured with a handler that includes the credentials.

     - A GET request is sent to the constructed URL.

     

    - Response Handling:

     - If the request is successful, the response is read and parsed as a JSON object using `JObject.Parse`.

     - The summary data is then printed to the console.

     

    Running the Example:

    - Replace the placeholder values (`<piwebapi_server>`, `<stream_id>`, `your_username`, `your_password`) with your actual PI WebAPI server details, stream ID, and credentials.

    - Run the project, and it should output the summary data in JSON format.

     

    Error Handling:

    - The example includes basic error handling to check the status of the HTTP response.

    - You may want to add more sophisticated error handling depending on your needs.

     

    This C# example demonstrates how to interact with the AVEVA PI WebAPI to request summary data for a specific stream. You can expand upon this example to handle different summary types, time ranges, or even to perform POST requests if needed.