Batch Reporting Example

This is a more complete example that actually does something with the data.

Whenever the batch code changes (and is not zero), a report will be created

#Import Trigger Libraries
import arditrigger
from arditrigger import trigger,data,delay,when,timer,risingedge

#Misc Libraries
import datetime

#Reporting & Query Libraries
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import mplreport
import ardiapi as ardi
#Required to prevent a warning being displayed
pd.plotting.register_matplotlib_converters()    

@trigger
@data('Manufacturing Center.Batch Number')
@risingedge
@delay(5)
@when(lambda o: o.Value() != o.OldValue() and o.Value() > 0)
def BatchReport(o):
    rng = o.Range(utc=True)
    print("Batch Found Between " + str(rng[0]) + " and " + str(rng[1]))

    try:
        #Get the batch ID.
        batchid = str(o.OldValue())

        #Don't process this batch if there's no valid ID.
        if batchid == "0":
              return

        #Create a report
        report = mplreport.MPLReport("Batch Report - " + batchid,"Batch Report " + batchid + ".pdf")
        fig,axes = report.CreatePage(1)

        #Draw the title for the report
        report.Title(rng[0],rng[1],override="Batch Report - " + batchid)

        api = o.GetARDIAPI()      

        #Get the speed of the process during this batch
        query = "('Manufacturing Center') ASSET ('Speed') PROPERTY VALUES {} GETHISTORY"

        #Limit the number of samples to the maximum for 300-dpi A4 paper
        samples = (rng[1] - rng[0]).total_seconds()
        if samples > 2400:
             samples = 2400

        #Just in case, use the long-term query engine (we can't always predict batch length).
        #The long term engine can deal with extremely long time-frames. 
        qry = api.StartQuery()
        req = qry.StartHistoryRequest(query,rng[0],rng[1])        
        req.samples = int(samples)

        #Make the actual query
        df = qry.GetHistory(req)        

        #Plot the speed 
        axes.plot(df[df.columns[0]])

        #Save the report
        report.Save()
    except:
        pass
arditrigger.Start("localhost","default")
#Comment the above line and uncomment this one to generate the last 2 days of data
#arditrigger.Backfill("localhost","default",datetime.datetime.now() - datetime.timedelta(days=2))

What It Does

In this example, the function is triggered whenever the batch number changes.

A report showing the production speed for each batch is created 5 seconds after each batch ends. The old value of the batch ID is used as the file name and heading of the report.

It's important to note that the old value(s) are used, because the report should include the name of the batch that is just complete, not the batch that just started.