TrentTelfer

Python & PI Code

Discussion created by TrentTelfer on Jul 28, 2014

I am absolutely shocked that PI doesn't have a python library or R library for data analysis, but that is another discussion altogether. I figured that since it took me a while to figure out how to retrieve data that I should probably share my script so others don't have to go through the pain. This script worked for me with python 2.7.6 and pywin32.

import time
from datetime import datetime, timedelta
from win32com.client import Dispatch


def get_pi_avg_data(database, start_time, end_time, pi_tag, interval):
    """
    :param database: DNS name of database as string object.
    :param start_time: Start time of interval as a datetime object.
    :param end_time: End time of interval as a datetime object.
    :param pi_tag: Tag name in PI database as a string object.
    :param interval: Interval of data required as a string object, i.e., 1d (one day), 1h (o                     ne hour).
    :return: Returns a list object as [date(datetime), value(float), quality(float)]
    """
    td_max = timedelta(minutes=15)
    pisdk = Dispatch('PISDK.PISDK')
    my_server = pisdk.Servers(database)
    con = Dispatch('PISDKDlg.Connections')
    con.Login(my_server,
              '',
              '',
              1,
              0)
    pi_time_start = Dispatch('PITimeServer.PITimeFormat')
    pi_time_end = Dispatch('PITimeServer.PITimeFormat')
    pi_time_start.InputString = start_time.strftime('%m-%d-%Y %H:%M:%S')
    pi_time_end.InputString = end_time.strftime('%m-%d-%Y %H:%M:%S')
    sample_asynch_status = Dispatch('PISDKCommon.PIAsynchStatus')
    sample_point = my_server.PIPoints[pi_tag]
    sample_values = sample_point.Data.Summaries2(pi_time_start,
                                                 pi_time_end,
                                                 interval,
                                                 5,
                                                 0,
                                                 sample_asynch_status)

    t0 = datetime.now()
    while True:
        try:
            valsum = sample_values("Average").Value  # retrieve the value
            break  # it will get out of infinite loop when there is no error
        except:  # it failed because server needs more time
            td = datetime.now() - t0
            if td > td_max:
                print "It is taking so long to get PI data ! Exiting now ...."
                exit(1)
            time.sleep(3)

    i = 1
    temp_data = []
    while i < valsum.Count+1:
        dt = datetime.utcfromtimestamp(int(valsum(i).TimeStamp))
        avg_value = valsum(i).Value
        quality = valsum(i).ValueAttributes('Percentgood').Value
        temp_data.append(dt, avg_value, quality)
        i += 1

    return temp_data

Credit: http://nquintos.blogspot.ca/2011/01/using-python-to-access-osi-softs-pi.html

Outcomes