================================================================

 Custom Scripts and REST API Endpoints

 Quick Start Guide

================================================================



THE BIG PICTURE

---------------


Stream SCADA lets you extend the platform with C# code in two

complementary ways. You don't need a separate IDE, build tool, or

deployment step — author the code in the Stream Designer and it

takes effect on the next server start.


The two things you can author:


  Library       Reusable code shared across all your scripts.

                   Lives at:  Project -> Scripts -> Library

                   Files:     Scripts/Library/*.scr


  REST API         Custom HTTP endpoints exposed by your Stream 

  Endpoints          server. Anyone with network access (and the right permissions) can call them.

                Lives at:  Project -> Integration -> REST API

                         Files:     Scripts/Endpoints/*.scr

                               URL:       http://your-server:port/api/endpoints/{name}


Think of it like this:


  Library  =  the helper functions you write once and reuse.

  Endpoints =  the doors you open in the wall so external tools

              (mobile apps, dashboards, Excel macros, integration

              partners) can talk to your plant.



================================================================

  PART 1 — LIBRARY (Shared Code)

================================================================



WHAT IT IS

----------


A Library file is a piece of C# code that defines reusable classes and methods. Anything you put here is automatically available to every other script in the project — Loose Scripts, Digital Block scripts, AND REST API Endpoints — by name, with no imports needed.


Use it for:

  - Math / formatting helpers (averages, units conversion, timestamp formatters)

  - Domain calculations (KPI logic, alarm priority rules)

  - Reusable Tag-I/O helpers ("get the average of these three sensor tags")

  - DTO classes that endpoints return


If you find yourself copy-pasting the same C# in two scripts, move it to a Library file.



HOW TO CREATE ONE

-----------------


1. In Stream Designer, expand:  Project -> Scripts -> Library

2. Right-click and choose "Add new Library File".

3. Name it something descriptive: Math2, TimeUtil, AlarmRules, PlantCalcs, etc.

4. The editor opens with a class skeleton. Fill in your methods.

5. Save.

6. Click "Check" to compile-validate. Green = ready.

7. Restart the Stream server for changes to take effect at runtime.

   (Library hot-reload is on the roadmap.)



EXAMPLE: A SIMPLE MATH HELPER LIBRARY

-------------------------------------


File: Scripts/Library/Math2.scr


    public static class Math2

    {

        public static double Average(params double[] values)

        {

            if (values == null || values.Length == 0) return 0;

            double sum = 0;

            foreach (var v in values) sum += v;

            return sum / values.Length;

        }


        public static double Round2(double x) => System.Math.Round(x, 2);


        public static double Clamp(double x, double min, double max)

        {

            if (x < min) return min;

            if (x > max) return max;

            return x;

        }

    }


After saving and restarting, you can call Math2.Average(...) from any other script in the project, no imports needed.



EXAMPLE: A TAG-AWARE LIBRARY

----------------------------


File: Scripts/Library/PlantCalc.scr


    public static class PlantCalc

    {

        // Returns the average of two tag values, or 0 if either tag

        // is unreadable.

        public static double AvgOfTags(string tagA, string tagB)

        {

            return Math2.Average(GetValueNum(tagA), GetValueNum(tagB));

        }


        // Determines if a temperature reading is in the alarm zone.

        public static bool IsTempInAlarm(string tagName, double max)

        {

            double t = GetValueNum(tagName);

            return t > max;

        }

    }


GetValueNum, SetValueNum, etc. are exposed automatically — same helpers you'd use in Loose / Digital Block scripts.



WHAT YOU CAN AND CAN'T DO IN A LIBRARY FILE

-------------------------------------------


YES:

  + Multiple classes per file

  + public static methods, properties, fields

  + Helper / DTO classes (public class MyData { ... })

  + Call any built-in: GetValueNum, SetValueNum, GetTVS, SetTVS,

    Stream.HTTP.GetCommand, Stream.FileSystem.WriteTextToFile, etc.

  + Use Newtonsoft.Json (JObject, JArray, JsonConvert)

  + Use any DLL you've placed in Scripts/Dlls/


NO:

  - Top-level statements (must be inside a class).

  - Files that mix class definitions with procedural code at the

    top level.

  - Namespace declarations (the engine wraps everything in a

    Library namespace automatically).



================================================================

  PART 2 — REST API ENDPOINTS

================================================================



WHAT THEY ARE

-------------


A custom HTTP endpoint is a piece of C# code that runs when a specific URL is hit. You write the body of a function; the platform takes care of:

  - Routing the URL

  - Parsing query strings and JSON bodies

  - Serializing your return value to JSON

  - Authentication (per project settings)


Use it for:

  - Mobile app or web dashboard backends

  - Integrations with ERP / MES / cloud platforms

  - Triggering plant actions from external workflows

  - Exposing computed metrics not stored as tags

  - File downloads (CSV reports, PDF exports)



HOW TO CREATE ONE

-----------------


1. In Stream Designer, expand:  Project -> Integration -> REST API

2. Right-click and choose "Add new REST API Endpoint".

3. Name it like a URL slug: getMaxTemp, computeAverage, acknowledgeAll, etc.

4. The editor opens with a procedural skeleton. Write your handler body.

5. Save.

6. Click "Check" to compile-validate. Green = ready.

7. Click "Play" to run the script with mock inputs and see the JSON result.

8. Restart Stream server (or leave it running — Endpoints compile lazily on first request).

9. Call from any HTTP client:

       GET  http://localhost:49110/api/endpoints/getMaxTemp

       POST http://localhost:49110/api/endpoints/getMaxTemp



EXAMPLE 1 — HELLO WORLD

-----------------------


File: Scripts/Endpoints/hello.scr


    string name = GetArgStr("name", "world");

    return new { greeting = "Hello, " + name + "!" };


Calls:


    GET  http://server:8585/api/endpoints/hello?name=Alice

    -->  { "greeting": "Hello, Alice!" }


    POST http://server:8585/api/endpoints/hello

    Content-Type: application/json

    { "name": "Alice" }

    -->  { "greeting": "Hello, Alice!" }



EXAMPLE 2 — READ A TAG

----------------------


File: Scripts/Endpoints/readTag.scr


    string tag = GetArgStr("tag");

    if (string.IsNullOrEmpty(tag))

    {

        return Response.BadRequest("Missing 'tag' query parameter.");

    }

    return new

    {

        tag,

        valueStr  = GetValueStr(tag),

        valueNum  = GetValueNum(tag),

        timestamp = TimeUtil.FormatNow()

    };


Call:


    GET .../api/endpoints/readTag?tag=Pump1.Speed

    -->  { "tag":"Pump1.Speed", "valueStr":"1450", "valueNum":1450,

           "timestamp":"2026-05-07 21:05:12" }



EXAMPLE 3 — WRITE A TAG (POST)

------------------------------


File: Scripts/Endpoints/writeTag.scr


    string tag    = GetArgStr("tag");

    double value  = GetArgNum("value");

    if (string.IsNullOrEmpty(tag))

        return Response.BadRequest("Missing 'tag'.");

    SetValueNum(tag, value);

    return new { written = true, tag, value };


Call:


    POST .../api/endpoints/writeTag

    Content-Type: application/json

    { "tag": "Setpoint.Furnace1", "value": 825 }

    -->  { "written": true, "tag": "Setpoint.Furnace1", "value": 825 }



EXAMPLE 4 — USING A LIBRARY METHOD

----------------------------------


File: Scripts/Endpoints/computeAverage.scr


    double a = GetArgNum("a");

    double b = GetArgNum("b");

    return new

    {

        a, b,

        average = Math2.Round2(Math2.Average(a, b))

    };


Math2 lives in Scripts/Library/Math2.scr. You don't import it —

it's just there.



EXAMPLE 5 — CONTROL HTTP STATUS / CONTENT TYPE

----------------------------------------------


File: Scripts/Endpoints/status.scr


    if (HasArg("fail"))

    {

        return Response.NotFound("requested failure");

    }

    return Response.Json(new

    {

        up = true,

        time = TimeUtil.FormatNow()

    }, status: 200);


Response.X(...) gives you fine control:


    Response.Json(obj, status)         JSON body

    Response.Text(text, contentType)   plain text / HTML / CSV

    Response.Html(html)                shortcut for text/html

    Response.File(bytes, "name.pdf")   file download

    Response.NotFound(message)         404

    Response.BadRequest(message)       400

    Response.Unauthorized(message)     401

    Response.Forbidden(message)        403

    Response.NoContent()               204

    Response.Redirect(url)             302

    Response.Status(code, body)        any code



WHAT'S AVAILABLE INSIDE AN ENDPOINT SCRIPT

------------------------------------------


Request data:


    Method               "GET" or "POST"

    Query                 query-string parameters as a dictionary

    Headers              request headers as a dictionary

    Body                   parsed JSON body (Newtonsoft JToken).

                               Null if the body is empty / not JSON.

    RawBody             raw body string (use for non-JSON bodies)


Argument helpers (look in Query first, then Body):


    HasArg("name")         bool — is the arg present?

    GetArg("name")         string  (default "")

    GetArgStr("name")     string  (default "")

    GetArgNum("name")  double  (default 0)

    GetArgInt("name")     int     (default 0)

    GetArgBool("name")  bool    (default false)


Tag I/O (same as anywhere in Stream):


    GetValueStr(tag)             string

    GetValueNum(tag)           double

    Val(tag)                          object — number or string depending on tag

    SetValueStr(tag, value)

    SetValueNum(tag, value)

    GetTVS(tag) / SetTVS(...)


Stream.* (full platform API):


    Stream.HTTP.GetCommand(url)

    Stream.FileSystem.WriteTextToFile(...)

    Stream.Mail.SendEmail(...)

    Stream.Application.GetTags()

    Stream.Computer.GetAvailablePhysicalMemory()

    ...and more — same surface as Loose/Digital Block scripts.


Returning:


    return ANY object  ->  serialized to JSON (200 OK)

    return null        ->  204 No Content

    return Response.X  ->  full HTTP control (see above)

    throw              ->  500 with the error type/message in the body



================================================================

  HOW LIBRARY AND ENDPOINTS WORK TOGETHER

================================================================


Recommended pattern:  THIN ENDPOINTS, FAT LIBRARIES


  - Put the real logic in a Library class.

  - Make the endpoint a one-or-two-line wrapper that pulls args out of the request and calls the Library.

  - This makes the same logic reusable by Loose Scripts, Digital Blocks, and any future scripts.


Bad (logic buried in the endpoint):


    File: Scripts/Endpoints/computeAvg.scr

        double a = GetArgNum("a");

        double b = GetArgNum("b");

        // ... 20 lines of computation ...

        return result;


Good (logic in the Library, endpoint exposes it):


    File: Scripts/Library/Math2.scr

        public static class Math2 {

            public static double Average(params double[] xs) { ... }

        }


    File: Scripts/Endpoints/computeAvg.scr

        return new { average = Math2.Average(GetArgNum("a"),

                                             GetArgNum("b")) };


Now a Loose Script can also call Math2.Average without duplicating the logic.


================================================================

  WHERE TO GO NEXT

================================================================


* Open the Stream Designer

* Project -> Scripts -> Library                      (write reusable code)

* Project -> Integration -> REST API            (write HTTP endpoints)

* Test endpoints from any HTTP client (Postman, curl, browser).

* Check the Stream log file for diagnostics if something doesn't

  behave as expected.


For platform-API documentation (the full Stream.* surface),

see the existing C# Scripting reference docs.