Quantcast
Channel: OSIsoft Users Community
Viewing all articles
Browse latest Browse all 1120

Example of usage of PIAPI with Python.

$
0
0

I recently had problems to backfill a tag in the PI.

To get around this I wrote a Python script that would like to share with everyone.

May be useful for someone.

Hugs.

# -*- coding: utf-8 -*-
import sys
import platform
import datetime
import time
from ctypes import *

ARRSIZE = 5000
ARCCODE = {
    'ARCTOTAL': 0,
    'ARCMINIMUM': 1,
    'ARCMAXIMUM': 2,
    'ARCSTDEV': 3,
    'ARCRANGE': 4,
    'ARCAVERAGE': 5,
    'ARCMEAN': 6
}
WARNING = """
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! WARNING: This program will erase data in archives!         !!
!! Make a full backup and verify its integrity before use it. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
"""


def pipt_findpoint(piapi, tagname):
    pointid = c_int()
    stat = piapi.pipt_findpoint(tagname, pointer(pointid))
    if stat != 0:
        print
        print("Error %d in findpoint for %s" % (stat, tagname))
        print
        sys.exit()
    else:
        return pointid


def main():
    if len(sys.argv) < 3:
        print
        print("Usage: python %s TAG start end" % sys.argv[0])
        print("Example: python %s sinusoid 01-jan-14 31-jan-14" % sys.argv[0])
        sys.exit()
    else:
        print(WARNING)
        answer = raw_input("Type YES if you are sure you want to continue? ")
        if answer.strip().lower() != "yes":
            print
            print("Thank you for not use this application. :D")
            print
            sys.exit()

        tagname = sys.argv[1]

        try:
            py_dti = datetime.datetime.strptime(sys.argv[2], '%d-%b-%y')
            py_dtf = datetime.datetime.strptime(sys.argv[3], '%d-%b-%y')

            dti_timestamp = int(time.mktime(py_dti.timetuple()))
            dtf_timestamp = int(time.mktime(py_dtf.timetuple()))
        except:
            print
            print("Start or end date format invalid. ")
            print("Use: dd-mmm-yy. Ex: 01-jan-14")
            print
            sys.exit()

        arch = platform.architecture()[0]
        if arch in ('32bit', '64bit'):
            piapi = windll.piapi
        elif arch == '32bit':
            piapi = windll.piapi32
        else:
            print
            print("Architeture not supported. :D")
            print
            sys.exit()

        pointid = pipt_findpoint(piapi, tagname)

        count = c_int(ARRSIZE)
        times = c_int * ARRSIZE
        rvals = c_float * ARRSIZE
        istats = c_int * ARRSIZE
        pitimes = times()
        pitimes[0] = c_int(dti_timestamp)
        pitimes[ARRSIZE - 1] = c_int(dtf_timestamp)
        stat = piapi.piar_compvalues(
            pointid, pointer(count), pitimes, rvals(), istats(), 0)

        if stat == -103:
            print
            print("No data for this point in this time range.")
            print
        else:
            for i in range(0, count.value):
                piapi.piar_deletevalue(pointid, pitimes[i])

            print
            print("All data between given dates for %s was deleted." % tagname)
            print

        # Here my rules to backfill :D
        if tagname.lower().strip() == "teste37":
            # Tag Monitored
            pointid_monitored = pipt_findpoint(piapi, "MONITORED-TAG")
            time_distance = datetime.timedelta(minutes=3)
            step = datetime.timedelta(minutes=1)
            val = None
            while py_dti <= py_dtf:
                # print py_dti

                avg = c_float()
                pctgood = c_float()
                time1 = py_dti - time_distance
                time1 = c_int(int(time.mktime(time1.timetuple())))
                time2 = c_int(int(time.mktime(py_dti.timetuple())))
                stat = piapi.piar_summary(
                    pointid_monitored,
                    pointer(time1),
                    pointer(time2),
                    pointer(avg),
                    pointer(pctgood),
                    ARCCODE['ARCAVERAGE']
                )

                if avg.value > 34:
                    nval = 1
                else:
                    nval = 0

                if nval != val:
                    print nval
                    stat = piapi.piar_putvalue(
                        pointid, c_float(nval), 0, time2, 0)
                    if stat != 0:
                        print
                        print("Error %d.")
                        print("When try add a new value to the Archive" % stat)
                        print
                        sys.exit()

                    val = nval

                py_dti = py_dti + step


if __name__ == '__main__':
    main()


Viewing all articles
Browse latest Browse all 1120

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>