JS Chain Observer for RackDevice (DrumRack)

Just Evan's icon

Hello.

I'm trying to make a device that dynamically monitors changes in the chains of the drumrack device, namely whether the name of any of the 128 (0-127) chain changes.

Since I am an absolute beginner in javascriprt, I made this script using chat GPT, this is all I could get out of it after spending a couple of months. It is also likely that the script is far from ideal.

I would like the script to display the id of the chains in which changes occurred and the new name of the chain (Chain: id N, Name Changed: New Name).

Perhaps someone can help me with this?

Thanks!

My script:

inlets = 1;
outlets = 1; // Set one outlet for sending chain ID

var observers = [];
var previousNames = []; // Array to store previous chain names
var pathPrefix = "";
var chainsObserver;
var maxChains = 128;

// Function to create an observer for a chain
function createObserver(index) {
    if (observers[index]) {
        observers[index].property = "";
    }
    var observer = new LiveAPI(callback, pathPrefix + " chains " + index);
    observer.property = "name";
    observers[index] = observer;
    previousNames[index] = ""; // Initialize previous name
}

// Callback function to handle name changes
function callback(args) {
    var index = args[0]; // Assume the first argument is the chain index
    var newName = args[1]; // Second argument is the new chain name

    // Check if the name has changed
    if (previousNames[index] !== newName) {
        previousNames[index] = newName; // Update previous name
        post("Chain ID: " + index + ", New Name: " + newName + "\n"); // Debug message
        outlet(0, index); // Send chain ID through the first outlet
    }
}

// Function to track changes in the chain list
function observeChains() {
    if (chainsObserver) {
        chainsObserver.property = "";
    }
    chainsObserver = new LiveAPI(chainsCallback, pathPrefix);
    chainsObserver.property = "chains";
}

// Callback function to handle changes in the chain list
function chainsCallback(args) {
    // Update observers only for active chains
    for (var i = 0; i < maxChains; i++) {
        if (i < args.length - 1) { // Check if the chain exists
            createObserver(i);
        }
    }
}

// Function to set the path and create initial observers
function setPath(path) {
    pathPrefix = path;
    observeChains();
}

// Message to set the path
function anything() {
    var args = arrayfromargs(messagename, arguments);
    outlet(0, args); // Send input message through the first outlet

    if (args[0] == "path") {
        var path = args.slice(1).join(" ");
        setPath(path);
    }
}

Note: In the inlet of the script I send a message containing the path to my drumrack, something like "path live_set tracks 0 devices 2"