Ankündigung

Einklappen

(KI-) Softwarelösungen

Um die Flut an (primär KI-erzeugter) Software zu kanalisieren, sind solche Lösungen ab sofort im Unterforum "Codeschnipsel" einzustellen. Bereits gepostete Themen werden sukzessive dorthin verschoben.
Mehr anzeigen
Weniger anzeigen

X1 Logic Node: Scripting - One block. Endless possibilities.

Einklappen
X
 
  • Filter
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge

    X1 X1 Logic Node: Scripting - One block. Endless possibilities.

    Introducing the SCRIPTING Logic Node for Gira X1 and L1​

    With the SCRIPTING Logic Node you can combine calculations, text processing and custom logic into a single powerful block, replacing multiple formula, formatter and parser modules at once. It can do JavaScript (ECMAScript 5.1), LUA Script 5.4 and even (on X1 only): Python 2.7 with a lot of additional libraries like paho/mqtt, pymodbus, bacnet, urllib2, urllib3, requests, jinja2, flask and more!
    The L1 can only do JavaScript and LUA Script, not Python, because it doesn't have enough resources.
    Use STATE to keep a value between triggers of the same block. This JavaScript counter starts at 1 on its first trigger:
    Code:
    STATE.count = (STATE.count || 0) + 1;
    OUT1 = STATE.count;
    To share a value, run SHAREDSTATE.x = 10; in one block and read OUT1 = SHAREDSTATE.x; in another.

    Build compact logic flows, reduce wiring complexity and create advanced automations with just a few lines of code. From smart data handling to dynamic text generation and complex conditions: everything runs inside one fast, flexible node.

    Finally, real JavaScript/LUA or Python scripting inside your logic project!​
    This logic node crushes the Formelberechnung​, Textformatierer, JSON-Parser and many other logic nodes with it's easy, flexible and lightweight use.

    One block. Endless possibilities.

    Write and keep your multiline source in a text file. In the script editor, select the language, paste your source and click the generated line to copy it. Select the same language in GPA and paste that line into Script. Pasting several lines directly into GPA 6.1 can leave only the first line.

    The logic node has an Auto Update Check (during validation in the GPA) and during operation on the X1/L1 so you will get notified of updates!
    Tip: Ask AI for a script (see below!)

    Download for your device
    X1 – JavaScript, Lua and Python 2.7
    L1 – JavaScript and Lua

    This Logic Node is now also available for Gira Homeserver, see here: https://knx-user-forum.de/forum/%C3%...tyserver-14362


    X1_Logic_Node_Scripting.png​

    How it works:​


    Send a value to Trigger to run the script. Zero and false also trigger a run. An input uses its configured default until it receives a value. If neither is available, the node supplies zero.

    Each trigger sends the outputs. To send 1 when numeric IN1 equals 5 and 0 otherwise, set OUT1 explicitly:
    Code:
    OUT1 = (IN1 === 5) ? 1 : 0;
    To forward only changed values, connect a Send-by-Change block to the output.

    Trigger the block when it received something at INPUT1? Do it like this:
    (don't worry about timing issues, it will first fill the inputs and then trigger the block)
    image.png​


    First test in GPA
    Add the block to a test logic sheet. Select JavaScript, one input and one output. Enter the line below, set numeric IN1 to 4 and send a value to Trigger in the simulation. OUT1 should report 5. Enable Debug to see the execution time on Error Text.
    Code:
    OUT1 = IN1 + 1;
    Some Javascript examples:



    NUMBERS
    Code:
    OUT1 = IN1 * 1.19;                        // Multiply with Mwst.
    
    OUT1 = IN1 + IN2 + IN3 + (IN4+2)           // Set Output sum.
    
    OUT1 = IN1 + IN2; OUT2 = IN1 - IN2;      // Set multiple outputs in one time
    
    OUT1 = (IN1 / 255) * 100;                        // Devide and use ( and )
    
    OUT1 = Math.round(IN1 * 100) / 100;        // Math.round will always round on whole number, to have two decimals, device by 100.
    
    OUT1 = Math.min(Math.max(IN1, 0), 100);    // Limit the Input between 0 and 100
    
    OUT1 = Math.abs(IN1);                    // Inverse: -5 -> 5
    
    OUT1 = -IN1;                            // Also 5 -> -5
    
    OUT1 = Math.pow(IN1, 2);                // (power of 2): IN1²
    
    OUT1 = Math.sqrt(IN1);                    // (taking the root): √IN1


    String manipulation (text)
    Code:
    OUT1 = "Hello there!";       // Set a simple text to Output1
    
    OUT1 = "Value is: " + IN1;             // Set combined text+value. Example: "Value is: 10"
    
    OUT1 = "My " + IN1 + " has " + IN2 + " homes"; // Concatenate Strings. Example: "My Son has 2 homes"
    
    OUT1 = IN1.toString().substring(0, 5);       // Take the first 5 characters (start at character 0)
    
    OUT1 = IN1.toString().trim();       // Trim spaces
    
    if (IN1.length > 10) OUT1 = IN1.substring(0, 10) + "..."; // Shorten text to 10 characters + "..."
    else OUT1 = IN1;
    
    OUT1 = IN1.replace(/,/g,".");       // Replace all commas by dots.
    
    OUT1 = IN1.slice(-3);                   // Keep the last 3 characters

    LOGIC
    Code:
    OUT1 = (IN1 === 1) ? 1 : 0;  // Compare a numeric input.
    
    var temp = IN1;
    OUT1 = temp;
    
    var i = 1;
    OUT1 = this["IN" + i];       // Read IN1 using its input number.
    
    if (IN1 >= 50) OUT1 = 1;        // Use if else
    else OUT1 = 0;
    
    if (IN1==1) OUT1 = 1;            // Use if, elseif, else
    else if (IN2==1) OUT1 = 2;
    else if (IN3==1) OUT1 = 3;
    else OUT1 = 0;
    
    if (OUT1==1 && IN2==0) OUT2 = 123;     // Read the value of OUT1
    
    switch(IN1) {                       // Switch Logic (easier than if/elseif/else)
      case 0: OUT1 = "OFF"; break;
      case 1: OUT1 = "AUTO"; break;
      case 2: OUT1 = "MANUAL"; break;
      default: OUT1 = "UNKNOWN";
    }
    
    for (var i = 1; i <= 5; i++) {        // A FOR Loop
      if (this["IN" + i] == true) {        // The computed variable IN1...IN5
        OUT1 = i;
        break;
      }
    }

    JSON
    Let's take the following sample JSON to explain:
    Code:
    {
      "device": {
        "name": "LivingRoomController",
        "status": "online",
        "metrics": {
          "temperature": 21.6,
          "humidity": 48,
          "power": 312.4
        },
        "modes": [
          { "id": 1, "name": "Auto", "active": true },
          { "id": 2, "name": "Eco", "active": false },
          { "id": 3, "name": "Boost", "active": false }
        ]
      }
    }
    Code:
    var obj = JSON.parse(IN1); // Read Input1 as JSON
    
    OUT1 = obj.device.name; // "LivingRoomController"
    
    OUT2 = obj.device.metrics.temperature; // 21.6
    
    OUT3 = obj.device.modes[0].name; // "Auto"
    
    OUT4 = obj.device.modes[2].active; // false
    
    OUT5 = obj.device.modes.length; // 3
    
    OUT6 = obj.device.status + " / " + obj.device.metrics.power + "W";

    Some LUA Script examples:​

    Use hysteresis for temperature control. OUT1 switches on below 20 and off above 22. Between those thresholds it keeps its previous value.

    ​
    Code:
    STATE.on = STATE.on or 0
    local t = IN1 or 0
    if t < 20 then STATE.on = 1 end
    if t > 22 then STATE.on = 0 end
    OUT1 = STATE.on
    ​

    Remember the lowest (OUT2) and Highest (OUT3) values in memory and also have the average of those two (OUT1)

    ​​
    Code:
    STATE.min = STATE.min or (IN1 or 0)
    STATE.max = STATE.max or (IN1 or 0)
    local v = IN1 or 0
    if v < STATE.min then STATE.min = v end
    if v > STATE.max then STATE.max = v end
    OUT1 = (STATE.min+STATE.max)/2   -- AVERAGE BETWEEN MIN AND MAX
    OUT2 = STATE.min                 -- The minimum value ever measured
    OUT3 = STATE.max                 -- The maximum value ever measured
    ​​


    Some Python 2.7 + packages Examples (X1 only!):​

    Using external Libraries (pymodbus, paho (mqtt) and requests with json)
    Read two holding registers. Replace the example IP address, unit and register addresses with those of your device.
    Code:
    # Read two holding registers and scale the results.
    from pymodbus.client.sync import ModbusTcpClient
    c = ModbusTcpClient("192.168.1.50", port=502)
    c.connect()
    raw1 = c.read_holding_registers(300, 1, unit=1).registers[0]
    raw2 = c.read_holding_registers(301, 1, unit=1).registers[0]
    OUT1 = raw1 / 10.0
    OUT2 = raw2 / 10.0
    c.close()

    Sending a message to a MQTT server with authentication:
    ​
    Code:
    # Send IN1 as Text to an MQTT Server
    import paho.mqtt.publish as publish
    publish.single(
    "home/scripting/test",
    payload=str(IN1), # send as text
    hostname="192.168.1.60",
    port=1883,
    auth={"username": "mqttuser", "password": "mqttpass"}
    )
    OUT1 = 1 # ok
    ​

    Requests and JSON with Python:
    ​
    Code:
    import requests
    OUT1 = 0
    try:
        response = requests.get("https://httpbin.org/json", timeout=5)
        OUT1 = response.status_code
        response.raise_for_status()
        OUT2 = response.json()["slideshow"]["title"]
    except Exception as error:
        OUT2 = str(error)
    ​



    You can even ask AI (ChatGPT, CoPilot or DeepSeek):

    "Hello, can you generate JavaScript code for the Gira X1 Scripting Logic Module (see examples at https://www.roelbroersma.nl/scripting)?
    I have 2 inputs and 1 output.
    • IN1 = weather information as text
    • IN2 = expected afternoon temperature (number)
    Requirements:
    • Output format: Temp: XX°C - DESCRIPTION
    • DESCRIPTION must be truncated to 20 characters and end with .. if longer
    • Use only plain JavaScript compatible with Jint
    • Assign the result to OUT1"


    CHANGE LOG

    v0.2.000000 (19-mar-2026)
    • Separated module for X1 and L1.
    • Both modules now support LUA Scripting!
    • X1 Module supports Python 2.7 with all basic libraries and paho/mqtt, requests, urllib2, urllib3, pymodbus, schedule, jinja2, flask, websocket, yaml, bacpipes (BacNet!) and much more.
    • Completely re-engineerd system for including packages.
    • Completely re-engineered separated worker process for Lua and Python scripting.
    • Timeout can be 0 (zero), for endless processes like receiving mqtt or a webserver!
    • Number of Inputs and Outputs can be 0 – 50 (instead of 1-50), so you can start a webserver or script without any input or output.
    • Triggering the Clear function will release the Worker process (handy when using timeout=0)
    • Implemented STATE memory (memory within the same block, so you can do: STATE.x = (STATE.x || 0) + 1; OUT1=STATE.x; to create a counter every time you trigger.
    • Implemented SHAREDSTATE memory (memory between multiple blocks!), so you can do: SHAREDSTATE.x = 5 in one block and use OUT1=SHAREDSTATE.x in another block.
    ​
    v0.1.000025 (23-feb-2026)
    • Feature: Set script timeout and see Execution time. Test it with a script like: for (i=1;i>0;i++) {let x=5;}​

    v0.1.000024 (02-feb-2026)
    • Fix: Update Notification in GPA (didn't work!).
    • Fix: You couldn't Trigger the block when not all inputs are set, fixed by pre-filling with 0 (zero).
    • Fix: A lot of small fixes ans possible NullPointerExceptions.
    • Feature: Implemented great Debug logging (enable Debug to see what's happening).
    • Feature: Debugging shows script execution time. (a hard limit is set at 200ms).
    ​
    ​v0.1.000018 (01-feb-2026)
    • Initial version
    • Tested on Gira GPA v6.0. X1: v3.0.52 and L1: v2.5.149, but may work on lower versions.




    ​
    Zuletzt geändert von Roeller; Gestern, 14:01.

    #2
    First comment reserved for future use

    Kommentar


      #3
      Second comment reserved for future use

      Kommentar


        #4
        Mega logic block. That simplifies things considerably!

        Kommentar


          #5
          Zitat von Roeller Beitrag anzeigen
          This logic node crushes the Formelberechnung​, Textformatierer, JSON-Parser and many other logic nodes with it's easy, flexible and lightweight use.
          OK, as the author of what you obviously perceive as your major "competition", let me say the following:
          1. Congrats for pushing the limits of what the X1/L1 can do with this really cool beast. If I had to choose but one of the third-party nodes it would probably be this one over even any of my own because of its endless flexibility.
          2. Its power and complexity may not always be needed. If all you need is a few calculations that can make nice use of built-in functions of Expression Calculator ("Formelberechnung"), it will be much simpler to use. For example, try to calculate a heating curve with JavaScript. You will end up with much more complexity than just using the ready-made function in Expression Calculator.
          3. Same goes for the others you mention, in cases where the combination of features simply isn't needed.
          Bottom line: You don't put me out of "business" (yet), but the bar has just raised. Next challenges:
          • Have all the builtins of Expression Calculator also available in "Scripting".
          • Open-Source "Scripting" to assure users it cannot simply go away or change its licensing.

          Kommentar


            #6
            Hi,

            very promising.

            Feature request: Add option to trigger on IN# value reception (specific or any).

            But: the in-operation update checker. A closed source scripting logic block communicating with online servers - not too attractive. I propose to remove this feature, along with making the logic node open source.

            See you
            Zuletzt geändert von maximilianeum; 02.02.2026, 10:17.

            Kommentar


              #7
              Zitat von hyman Beitrag anzeigen

              OK, as the author of what you obviously perceive as your major "competition", let me say the following:
              When I say crushing, it’s of course meant in a playful way, we’re not competitors, but friends on the same platform. And friends help friends by pushing the ecosystem forward together.​

              It would be great to see Gira occasionally release official logic building blocks as well, with a small dedicated team of enthusiastic developers focused purely on creating and improving these tools. In the meantime… it’s up to us.

              Agreed: scripting is not a replacement for all native blocks, but a flexible addition.

              I’ve been building tools and logic for both the HomeServer and the X1/L1 platform for over 15 years now, so this comes from long-term involvement and passion for the ecosystem. I’ve never charged money for any of this work and don’t plan to do so for current projects either. Regarding an “official license” (MIT, Apache, Creative Commons, etc.): I honestly hadn’t thought about that yet, good point!

              The update check is something I try to build into all blocks because there currently is no native Gira mechanism for this. Hopefully this will be integrated into GPA someday (and I hope via their own infrastructure). You don’t want to manually browse logic node websites and forum threads every few months just to check for updates.
              It currently does two things:
              1. Check the version during project validation (in GPA) and raises an error when an outdated version is detected.
              2. Check the version about once a week and give and sets the “Update available” output to 1. You can connect the update to a mail or notification block so you know there is an update. That's automation

              Teaser: Currently I’m working on another building block which I’ll try to release this week, for DUCO ventilation systems. These systems offer both API and Modbus, but the module I’m building makes integration extremely simple: it automatically discovers the unit via mDNS and does not require API authentication because it uses Modbus on the underlying layer. You can connect a DUCO system within minutes! A huge difference compared to manual API parsing or Modbus address mapping. When the IP of the Duco box changes,.. no problem.. it gets the new IP address.
              And yes: thas module will also be (and stay!) free.


              Kommentar


                #8
                Zitat von maximilianeum Beitrag anzeigen
                Hi,

                very promising.

                Feature request: Add option to trigger on IN# value reception (specific or any).
                See you
                I first had the same idea, but this can be easily done with 1 line, see this example:

                image.png​


                Kommentar


                  #9
                  Great work! An obvious question. Are you thinking about developing a similar node for the Homeserver?

                  Kommentar


                    #10
                    Update:

                    v0.1.000024 (02-feb-2026)
                    • Fix: Update Notification in GPA (didn't work!).
                    • Fix: You couldn't Trigger the block when not all inputs are set, fixed by pre-filling with 0 (zero).
                    • Fix: A lot of small fixes ans possible NullPointerExceptions.
                    • Future: Implemented great Debug logging (enable Debug to see what's happening).
                    • Future: Debugging shows script execution time. (a hard limit is set at 200ms).
                    ​
                    I noticed that I accidentally uploaded version v0.1.000006 (a pre-release version, with the name v0.1.000018 in the link) which was cached by Cloudflare...
                    The update-notification is not even working in that version, so you won't see there is an update. (murphy's law )

                    Kommentar


                      #11
                      Zitat von Roeller Beitrag anzeigen
                      Fix: You couldn't Trigger the block when not all inputs are set, fixed by pre-filling with 0 (zero).
                      Pre-fill with configurable value is a feature that all inputs have. When this is filled out by the user, will this override the 0 (zero)? If not, that could be confusing.

                      Related questions: Do inputs have a fixed type? If so, how is the type determined? If the type is non-numeric, what is the effect of pre-filling with 0? If there is no fixed type, can pre-filling with 0 cause problems when inputs are used in operations that don't work with a numeric type?

                      Zitat von Roeller Beitrag anzeigen
                      possible NullPointerExceptions
                      You must, positively, catch all exceptions that the user script could ever throw. Ideally you would output according error messages to separate outputs (which according to your first screenshot appear to already exist). If you don't, debugging a script, based only on guesswork, will be near to impossible. That's something I learned the hard way when implementing the Expression Calculator ("Formelberechnung").
                      Zuletzt geändert von hyman; 03.02.2026, 20:15.

                      Kommentar


                        #12
                        Zitat von hyman Beitrag anzeigen
                        Pre-fill with configurable value is a feature that all inputs have. When this is filled out by the user, will this override the 0 (zero)? If not, that could be confusing.
                        You can immediatelly Trigger the block, without all inputs having a value. That's a feature! (so the triggering will not be delayed untill all inputs have a value)
                        YES, if an input is not set, it will be filled with 0. If the user did set a default input, we will ofcourse not overwrite it with 0.

                        Zitat von hyman Beitrag anzeigen
                        Related questions: Do inputs have a fixed type? If so, how is the type determined? If the type is non-numeric, what is the effect of pre-filling with 0? If there is no fixed type, can pre-filling with 0 cause problems when inputs are used in operations that don't work with a numeric type?
                        No, Inputs can be any type: String, Integers, Double's, Floats, Temperatures, Booleans, whatever you like.
                        Outputs can also be any Type and it's unrelated to the Inputs. So an input can be Boolean and an output can be String.
                        The first time you connect something to the input, the Type is given to that input: So if you connect a Boolean, it is Boolean. If you connect a Integer, it's an Integer. If you connect a Text String, it's a Text String.

                        When you connect an input, you can (always) manually set the default value, you can set: 0, 10, "test", whatever you like. But if you didn't set a default value AND there is nothing received at the input yet, the input will be 0.
                        With numeric inputs, this adds the two values:
                        Code:
                        OUT1 = IN1 + IN2;
                        For a boolean input, this sends a text result in both cases:
                        Code:
                        OUT1 = IN1 ? "ok" : "off";
                        To append text, convert the input to a string. An unset input with no configured default gives "0test":
                        Code:
                        OUT1 = String(IN1) + "test";
                        To compare values in JavaScript, write the inequality operator as one token:
                        Code:
                        if (OUT1 !== IN1) {
                            OUT1 = IN1;
                        }
                        So if it runs for the first time and doesn't have an output, we make it 0 too
                        After the first run, the output is saved



                        Zitat von hyman Beitrag anzeigen
                        You must, positively, catch all exceptions that the user script could ever throw. Ideally you would output according error messages to separate outputs (which according to your first screenshot appear to already exist). If you don't, debugging a script, based only on guesswork, will be near to impossible. That's something I learned the hard way when implementing the Expression Calculator ("Formelberechnung").
                        I do, there is a lot of try/catch and offcourse the DEBUG output. When you turn it on, it will also tell you if it set the Input to a value of 0 (when it does not have anything) and even when it assumes that the output is 0 (if it didn't have a value before).

                        Happy SCRIPTING!
                        Zuletzt geändert von Roeller; Gestern, 14:02.

                        Kommentar


                          #13
                          UPDATE:
                          I know you’re already hyped about the SCRIPTING block… but this will make you freak out and unleash your weekend

                          I just dropped Version 2 on earth, it comes straight out of heaven..! More powerfull than ever!

                          Use full python or LUA script on the X1 and use pymodbus, paho/mqtt, bacnet or other python libraries. It also features MEMORY, so the block can remember previous states/variables. But even better: It features SHARED MEMORY, so other blocks know the variable you use in other blocks.. See the changelog here:

                          This isn’t an upgrade. It’s total madness


                          Changelog

                          v0.2.000000 (19-mar-2026)
                          • Separated module for X1 and L1.
                          • Both modules now support LUA Scripting!
                          • X1 Module supports Python 2.7 with all basic libraries and paho/mqtt, requests, urllib2, urllib3, pymodbus, schedule, jinja2, flask, websocket, yaml, bacpipes (BacNet!) and much more.
                          • Completely re-engineerd system for including packages.
                          • Completely re-engineered separated worker process for Lua and Python scripting.
                          • Timeout can be 0 (zero), for endless processes like receiving mqtt or a webserver!
                          • Number of Inputs and Outputs can be 0 – 50 (instead of 1-50), so you can start a webserver or script without any input or output.
                          • Triggering the Clear function will release the Worker process (handy when using timeout=0)
                          • Implemented STATE memory (memory within the same block, so you can do: STATE.x = STATE.x+1; OUT1=STATE.x; to create a counter every time you trigger.
                          • Implemented SHAREDSTATE memory (memory between multiple blocks!), so you can do: SHAREDSTATE.x = 5 in one block and use OUT1=SHAREDSTATE.x in another block.
                          ​
                          ​
                          Zuletzt geändert von Roeller; 21.03.2026, 16:12.

                          Kommentar


                            #14
                            Zitat von Roeller Beitrag anzeigen
                            I just dropped Version 2 on earth
                            Great Job, thank you for developing and sharing!
                            Gruß Bernhard

                            Kommentar


                              #15
                              Is there a small copy&paste error in the string examples?
                              Code:
                              OUT1 = IN1.toString().substring(0, 5);    // Take the first 5 characters (start at character 0)
                              
                              OUT1 = IN1.toString().substring(0, 5);    // Trim spaces​
                              Gruß Bernhard

                              Kommentar

                              Lädt...
                              X