This blog series is about an open source project "Script scheduler" I worked on recently, it allows to run scheduled and triggered scripts (jobs).

 

The series contains the following parts:

 

Periodic YouLess example

This more advanced example reads data from an IOT energy monitor device in my company office building named YouLess.  It checks the consuming Watts for usage peaks and writes an event frame to an AF database if a peak is detected.

Below is the full TypeScript code:

 

The code that is new is explained in the following steps:

 

1: The script starts with importing external dependencies that are used in the code:

New in this algorithm are:

  • Line 2 is required to have a typed job definition in the run function.
  • Line 9 is required to have a typed interface definition for the data return by YouLess
  • Line 12 is required to be able to create an EventFrame instance
  • Line 14 is required to be able to make http requests to the YouLess compatible with async/await.

 

2: The config object:

In this example the cron notation for a interval of 2 seconds is used.

 

3: Using the run function to get YouLess data:

The run method is now defined as type of Agenda.Job.

For getting the data from YouLess a get request is done asking for a json format in line 33.

The resulting string is parsed to JSON in line 35 and stored in the youLessData constant with the type IYouLess.

In lines 37 and 38 a condition is checked if currently a Watt Peak is detected. Because of the known type we can access the pwr attribute with dot notation:

 

4: Using the run function to create and store an Event Frame in AF:

Two cases are checked:

  1. When a watt peak is detected a new EventFrame is created with a Name, StartTime and Description in lines 43 - 48 but only when nothing is locally stored in "job.attrs.data".
  2. If a watt peak is not detected and a locally stored EventFrame exists in "job.attrs.data" the frame is closed with a EndTime and the PIWebAPI service is used to store the frame in a defined AF database. The locally stored frame is set to null so a new detection can happen in future runs of the algorithm.

 

5: The algorithm in action:

A breakpoint is hit when a new Event Frame is created to be locally stored until finished.

 

Because the persisting of jobs is done in MongoDB, I can browse through this database and see this job with the stored Event Frame in the data attribute using the tool Robomongo

 

After some minutes a few event frames show up in the AF Explorer!

 

David Golverdingen @ Magion

 

Continue reading with Part 3 - Advanced example: "Triggered HelloSinusoid" (Writing PIWebAPI channel triggered Sinusoid data to CSV)