IMD SolutionComputing LibraryShop main store

How-to

Export CSV when a Canary historian event closes a batch

Edge computing and IIoT Published 6 min read

Short answer

Canary has no built-in trigger that exports CSV when a batch completes. The export client reads the closed event's start and end timestamps, from the events query in the Read API or from an external SQL events table, pulls the tag data for exactly that range resampled at your CSV interval, and writes a file named from the event. Wait one to two minutes past the event close, and page a 7-hour, 1-second, 40-tag pull into hour blocks.

On this page
  1. Where the event boundaries live
  2. Poll the event store; do not wait for a push
  3. Pull the tag range without ragged rows
  4. Size and page the request
  5. Write the file so a rerun cannot corrupt it
  6. Verify end to end against the dashboard
  7. The decision
  8. Questions asked

Canary has no built-in job that watches a batch-complete condition and drops a CSV on a share. What it gives you instead is both halves of the problem: the historian writes an event when the batch starts and closes it when the batch finishes, and the Read API serves tag data for any time range you ask for. A small scheduled client, a script or a Windows service, that reads the closed event's start and end timestamps, pulls the tag range, and writes the file does the entire job. The steps below are the commissioning order; prove each one before wiring the next, or a missing row will leave you guessing whether the event query, the data query, or the file writer dropped it.

Where the event boundaries live #

By default, Canary stores events in a SQLite database. That is enough for dashboards to render them, and the Read API exposes events for query either way, but a file database behind a running service is a poor polling target. Do not open the events file with your own SQL process while the historian service is running: you can lock the service out or read a torn copy. The supported alternative is to configure event storage into an external SQL database, which gives you an ordinary table you can index, join to your batch or recipe metadata, and poll from any scheduler.

The decision: choose external SQL when the export client is a scheduled SQL process or needs to join events to a batch number; stay on the events query in the Read API when the client is already an HTTP client and you would rather not manage database credentials on the historian.

Check before moving on: run one event query, REST or SQL, and confirm it returns the most recent completed event with a non-null end timestamp, its event type, and whatever identifier separates product A from product B. If the end timestamp is null on a batch you know is finished, the event never closed, and no export logic downstream will fix that.

Poll the event store; do not wait for a push #

A 30- to 60-second poll against the events store costs nothing and survives a client restart. A database trigger firing an external process fails silently on the one night the network share is unreachable, so poll.

With external SQL storage the poll is one SELECT; the column names below are illustrative, so read them from your own schema:

SELECT event_id, start_time, end_time, event_type
FROM canary_events
WHERE end_time IS NOT NULL
  AND exported = 0
ORDER BY end_time ASC;

Two boundary conditions bite. First, an event closes the instant the trigger condition clears, but the last samples for that timestamp may still be in flight from the collector: wait one to two minutes after the close before you pull data, or request data to an end time slightly past the event's end. Second, a batch still running has no end timestamp, so the non-null filter is what keeps a partial CSV from being written mid-batch. If the poll runs as a stored query with time-boundary filters on a reporting front end, off-by-one errors at the boundary are the usual first fault; the same boundary pattern is covered in this fix for Ignition named query shift boundary SQL errors.

Check: close a short test event and confirm the poll picks it up exactly once, and that the next cycle returns nothing.

Pull the tag range without ragged rows #

Authenticate to the Read API first. It issues a session token that later calls carry and that expires when idle, so the client must refresh it rather than cache it forever. Browse the tag list once during commissioning and configure the tag set; do not browse on every run.

The trap is raw data. A historian that stores on exception returns each tag at its own timestamps, so a raw multi-tag pull over a batch gives you a sparse result with one populated cell per row: correct, and useless in Excel. Request the resampled form at a fixed interval instead. Every tag then lands on the same timestamp grid, and the CSV gets one row per interval and one column per tag. If the batch file should be coarser than the stored data, the request interval controls it; exporting a historian trend CSV at one-minute intervals works the same way.

Size and page the request #

Work through the size before you trust one big call. Worked example: a 7-hour batch, a 1-second CSV interval, 40 tags.

  • Duration: 7 h multiplied by 3600 s/h gives 25,200 s, so 25,200 timestamps per tag.
  • Values in one pull: 25,200 timestamps times 40 tags gives 1,008,000 values.
  • Paged by hour blocks: 3600 s times 40 tags gives 144,000 values per block, and the batch needs 7 blocks.

Page by time, not by row count, so a failed block retries one hour of data instead of the whole batch. Then check the row count: it should equal the duration divided by the interval, plus or minus one for boundary inclusion, which is 25,200 plus or minus 1 here. If it comes back short, the server truncated the response and you must page smaller.

Write the file so a rerun cannot corrupt it #

Name the file from the event, not from the clock: product code, event identifier, start time, for example batchA_10423_2024-05-14T0630.csv. Two batches of the same product finishing in the same hour otherwise overwrite each other. Write to a temporary name in the destination folder and rename on completion, because a half-written CSV that the process owner opens looks like data loss.

Set the exported flag, or write to a companion table if you cannot add a column, only after the rename succeeds. That ordering makes the job safe to kill and restart: the same batch re-exports cleanly and leaves exactly one file.

Decide once whether the CSV carries UTC or plant local time, and verify it rather than assume it. Take one known event boundary, read how the dashboard displays it, and compare with what the API and the events table return. A display-layer offset would shift every CSV timestamp, and by a different amount across a daylight-saving change.

Verify end to end against the dashboard #

Run the finished job against a batch that has already completed and been reviewed on the dashboard, then check five points:

  1. The first and last CSV timestamps match the event start and end shown for that batch, within one interval.
  2. Three tags at three timestamps spread across the run match the dashboard trend values. A mismatch on all three means a timezone offset; a mismatch on one means you aggregated where the dashboard interpolates.
  3. The column count equals the configured tag count plus the timestamp column, with no tag silently dropped because it did not exist for the whole span.
  4. The row count equals the duration divided by the interval.
  5. Kill the client mid-export and restart it: exactly one file results, with no duplicates.

The decision #

Build the export as a 30- to 60-second poll of the events store: external SQL if you join to batch metadata, the Read API events query if you do not. Wait one to two minutes past the event close, pull the tag range resampled at your CSV interval in hour-sized blocks, and write to an event-named file with the exported flag set only after the rename. That client replaces the missing out-of-the-box trigger and survives a restart at any point in the job.

Questions asked

Where do the batch start and end times come from in Canary?

The historian writes one event when the batch starts and closes it when the trigger condition clears; the end timestamp stays null until then. Read the two timestamps with the events query in the Read API, or configure event storage into an external SQL database and select them from that table. A batch that is still running has no end timestamp, so filter on a non-null end time before exporting.

Why does my multi-tag CSV have one filled cell per row?

Data stored on exception keeps each tag on its own timestamps, so a raw pull returns a sparse result. Ask the Read API for the resampled form at a fixed interval instead: every tag then shares one timestamp grid, and the CSV gets one row per interval and one column per tag. That interval also sets the CSV row count, so pick it before sizing the request.

How large can one data query be before it must be paged?

For a 7-hour batch at a 1-second CSV interval over 40 tags, a single pull is 25,200 timestamps times 40 tags, about a million values. Page by hour blocks, 3,600 timestamps and 144,000 values each, seven blocks per batch, so a failed block retries one hour of data instead of the whole batch. Verify the returned row count as duration divided by interval, within one row.

How do I stop the job from exporting the same batch twice?

Add an exported column to your external events table, or write to a companion table if you cannot change the schema, and set it only after the CSV rename succeeds. Name the file from the event identifier and start time, not from the clock. With that ordering you can kill the client mid-export and restart it, and each batch still produces exactly one file.

Can a database trigger start the export instead of polling?

It can, if events are configured into an external SQL database, but polling is the safer design. A trigger fires inside the events database and has no way to retry when the export client or its network share is down, so the batch is silently missed. A 30- to 60-second poll survives a restart and picks up any event whose exported flag is still unset.

Keep reading

  • How-to

    How to move Wonderware Historian data into Canary Historian

    Yes. Backfill Wonderware history by exporting CSV files or a SQL database that Canary consumes, run a parallel real-time collection path for the same tags, and verify record counts and values at the timestamp where imported history meets live data.

    Edge computing and IIoT

  • How-to

    Backfilling trend history from a plant historian

    Yes, you can backfill trend history from a plant historian into a SCADA server. Extract the stored records through the historian's native export or ODBC interface, map each source point to its destination object with original timestamps and quality, insert the batches through the destination's documented history methods, and prove the import by reading the interval back from the destination. A saved CSV is a bridge, not proof of import.

    Edge computing and IIoT

  • How-to

    Export historian trend CSV at one-minute intervals

    Export the trend's recorded values and you get change-based events, about 17 minutes apart in this case, because the historian stores a value only when it changes. To get one row every minute, query the tag in the Query tool with regularly spaced retrieval at a 60-second interval and export that result; the grid comes from retrieval, not storage.

    Edge computing and IIoT

Build multidimensional arrays in Node-RED for InfluxDB writes