Split (or similar function) in rule (Javascript)

I need to extract the third number from an expression like 22,33,44 (the brightness of a hue-lightbulb).
In YAML …state.split(",")[2] would do the job.
But don’t know how to transfer this to Javascript in a rule. From a Javascript documentation I got this idea (which doesn’t work):

test = itemRegistry.getItem("LeuchteHuegross_Farbe").getState();
test2 = test.split(",");  // <-- this doesnt work
//test3 = test2[1];       (or [2], don't know and can't test this because of the line above not working

eventually the code should be in one line, this is divided in separate lines for testing purposes …

Do you have any idea how to work with split or a different (and simple?) solution?

Doesn’t work how? Fails to split the string in the way expected? Fails to run at all? Errors in the log?

What type of Item is this? If it’s a Color Item then the State is not a String. It’s a HSBType. You can only do String operations on Strings. If it is an HSBType then you can just call .getBrightness() to get the brightness value.

And there is no reason to pull the Item from the registry just to get its state.


is equivalent to


If you want to split a string item that is not hsbtype it can be done this way. For future reference.

var test = itemRegistry.getItem("LightHall_Lighthallcolour").getState().toString().split(",");
logger.info("Test " +  test);
logger.info("Test0" +  test[0]);
logger.info("Test1" +  test[1]);
logger.info("Test2" +  test[2]);

Gives this result:
Test 128,100,89
Test0 128
Test1 100
Test2 89

This is the HSB way:

logger.info("Hue " + items["LightHall_Lighthallcolour"].getHue());
logger.info("Saturation " + items["LightHall_Lighthallcolour"].getSaturation());
logger.info("Brightness " + items["LightHall_Lighthallcolour"].getBrightness());

Which gives this:
Hue 128
Saturation 100
Brightness 89


Thank you for your help, @rlkoshak and @ubeaut !

I just recently started with OH. And with rules just a couple of days ago (until now I used node red), so I appreciate your support and you may better understand the following (which otherwise might seem quite stupid, my recent experiences with OH sure make me feel that way…)

  • I didn’t know so far that I can refer to an item with an expression like items[“LeuchteHuegross_Farbe”]; it’s certainly more easier to read. Are there other advantages (like speed)?
  • the conversion to string helped, something like this basically seems to work (at least once, see later):
var testx = itemRegistry.getItem("LeuchteHuegross_Farbe").getState().toString().split(",");
testx = testx[2];             // <-- works
events.sendCommand("v_string",testx);          //<-- works - and then again, it doesnt any more
  • the .getBrightness()-function should be the ideal version for what I want to do, but so far I didn’t get that running which leads to the core of my problem

I seem to have a fundamental problem with my OH-installation (tried to describe it here: OH freezing - until reboot - #3 by Ursusprimus); one of the problems is, that OH seems to break but I don’t notice immediately. Probably because it still runs in the browser. So I do some coding and wonder why nothing happens with the addressed-items, thinking I made a mistake. After a while I check (by now I got used to it and to it regularly) by trying to open OH in another tab, when it’s not opening, I reboot and then at least I can continue. But as it takes some minutes, it’s quite annoying/frustrating …
However, with some of my rules (as above) a reboot doesn’t help so I thought it must be a problem of the code. Strangely, it sometimes (at least once, as written above) it changed the item, later it didn’t any more. Not even after a reboot. This leaves me somewhat confused/irritated.
As of how to find if an item has changed, I see these options/problems:

  • developer sidebar: Pinned objects (doesn’t update regularly); code tools with “=items.name.state” (doesn’t seem to be updating regularly either)
  • looking at the item in settings/items/ ← quite cumbersome but here at least I notice when the window doesn’t update that I might have to reboot, so that’s what I’m doing at the moment.
  • karaf console (new to me, checked it because you mentioned “logger”): openhab:status itemname
  • maybe tailgate (:9001)

So I have a combination of a fundamental problem (OH-not working like it should), a concrete problem (it value not changing consistently) and a lack of experience/knowledge (programming and error-finding).

To clarify things, here some screenshots.

  1. Using OH, I set the lamps brightness to 83 (which worked on the lightbulb and the item):
  2. trying the code doesn’t update v_string regularly (it sometimes does, right now it doesn’t, even after reboot; tried several versions, now as //comment)
    Here the definition of v_string:
anzahl = 0;

//var testx = items["LeuchteHuegross_Farbe"] //<-- works as a replacement for item.Registry
var testx = itemRegistry.getItem("LeuchteHuegross_Farbe").getState().toString().split(",");
testx = testx[2];             // <-- works
events.sendCommand("v_string",testx);          //<-- works - and then again, it doesnt any more

//var testx=items["LeuchteHuegross_Farbe"].getBrightness();    //doesnt seem to work, strange?   - maybe it would work
//testx = itemRegistry.getItem("LeuchteHuegross_Farbe").getBrightness();  /doesnt work either

/*   don't know where/how to find logger info -- not in fronttail (:9001) and in karaf console I don't know the command to see the output of "info"
var test = itemRegistry.getItem("LeuchteHuegross_Farbe").getState().toString().split(",");
logger.info("Test " +  test);
logger.info("Test0" +  test[0]);
logger.info("Test1" +  test[1]);
logger.info("Test2" +  test[2]);

I’m not sure where to see the logger info:

  • karaf console? which command to access this?
  • tailgate? didn’t find anything related when filtering for test:

And two last screenshots showing different values:


Maybe you have an idea what I could try …

1 Like

The thing I used as an example looks like this:

When you add the channel to the thing make it like this:

For logging use this command in Linux:

tail -f /var/log/openhab/openhab.log

It gives a live output similar to below:
2021-04-10 16:01:11.623 [INFO ] [org.openhab.rule.a5b309456d ] - Back door opened
2021-04-10 16:01:12.268 [INFO ] [org.openhab.rule.a118e0e70d ] - Back door opened
2021-04-10 16:01:54.407 [INFO ] [org.openhab.rule.a5b309456d ] - Back door closed
2021-04-10 16:01:55.049 [INFO ] [org.openhab.rule.a118e0e70d ] - Back door closed
2021-04-10 16:42:20.206 [INFO ] [org.openhab.rule.a118e0e70d ] - Lights lounge ON
2021-04-10 16:54:52.025 [INFO ] [org.openhab.rule.a118e0e70d ] - Lights lounge OFF
2021-04-10 17:04:05.510 [INFO ] [org.openhab.rule.a5b309456d ] - Front door opened
2021-04-10 17:04:06.752 [INFO ] [org.openhab.rule.a118e0e70d ] - Front door opened
2021-04-10 17:04:13.908 [INFO ] [org.openhab.rule.a5b309456d ] - Front door closed
2021-04-10 17:04:15.142 [INFO ] [org.openhab.rule.a118e0e70d ] - Front door closed

I get the impression that this commands gets me the same (more or less) output like in fronttail log viewer.

I get none of the output in the log with your programming proposal like you did (used search). So seems to be my flawed system …

The frontail does the same thing.
I ssh to the openhab server and run the the tail command.

First, almost never is speed of something like this something you need to concern yourself with. There main advantage of it’s shorter and all you need is the name of the item.

As for the rest, you need to be constantly monitoring the logs. You need to add logging to your rules and watch the logs for those as well. Pay attention to all errors. Try to understand what they mean and ask if you can’t figure out what they mean.

Writing rules without watching the logs is like driving a car blindfolded.

When asking for help, post the relevant logs but as text with code fences.

code or logs go here

Based on just the description we are powerless to help.

To be more systematic, I

  1. First ran these commands (again):
var test = itemRegistry.getItem("LeuchteHuegross_Farbe").getState().toString().split(",");
logger.info("Test " +  test);
logger.info("Test0" +  test[0]);
logger.info("Test1" +  test[1]);
logger.info("Test2" +  test[2]);

events.sendCommand("v_string", test[2]);  
  1. Then I downloaded these logfiles: openhab.log.7; events.log; openhab.log
    and quick searched them and fronttail for “Test2” (and for v_string, too). No matches.
    → I’d have expected one of them to appear somewhere, so I can’t give any more info.

Given that, I think it would make sense to address the fundamental problem described above first. Maybe you (or someone else) could help me with that (although this isn’t the perfect post, but since I described so much about the problem already, I’ll continue here. I can copy it to the other post if you think this would be more appropriate).

I upload the 3 mentioned logfiles. But here’s what I think might be relevant, although I lack the expertise to interpret these messages:

  1. openhab.log.7
2021-04-11 08:27:06.911 [WARN ] [.transport.servlet.ServletController] - Can't find the request for http://openhabian:8080/rest/events's Observer 
2021-04-11 08:27:30.384 [ERROR] [org.openhab.binding.mqtt            ] - bundle org.openhab.binding.mqtt:3.0.1 (267)2021-04-11 08:27:30.384 [ERROR] [org.openhab.binding.mqtt            ] - bundle org.openhab.binding.mqtt:3.0.1 (267)[org.openhab.binding.mqtt.internal.discovery.MqttServiceDiscoveryService(326)] : The activate method has thrown an exception
java.lang.IllegalArgumentException: ID segment 'MQTT System Broker' contains invalid characters. Each segment of the ID must match the pattern [\w-]*.
	at org.openhab.core.common.AbstractUID.validateSegment(AbstractUID.java:98) ~[?:?]
2021-04-11 08:27:31.518 [WARN ] [ache.cxf.phase.PhaseInterceptorChain] - Interceptor for {}WebClient has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Could not send Message.
	at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:67) ~[bundleFile:1.0.9]
2021-04-11 08:27:32.393 [WARN ] [b.client.internal.InfluxDBClientImpl] - The exception occurs during check instance readiness
com.influxdb.exceptions.NotFoundException: null
	at com.influxdb.internal.AbstractRestClient.responseToError(AbstractRestClient.java:104) ~[bundleFile:?]   ...
2021-04-11 08:27:32.845 [WARN ] [rnal.influx2.InfluxDB2RepositoryImpl] - database not ready
2021-04-11 08:27:32.951 [ERROR] [nal.common.AbstractInvocationHandler] - An error occurred while calling method 'QueryablePersistenceService.query()' on 'org.openhab.persistence.influxdb.InfluxDBPersistenceService@9a7089': null
com.influxdb.exceptions.ForbiddenException: null
	at com.influxdb.internal.AbstractRestClient.responseToError(AbstractRestClient.java:102) ~[?:?]

2021-04-11 08:49:03.285 [WARN ] [persistence.jdbc.internal.JdbcMapper] - JDBC::openConnection: no driver available!

this goes on for many lines, but they mostly seem to be repetitions

  1. openhab.log
    seems to be about the same like in openhab.log.7

  2. events
    nothing special. I think this is the file where v_string and the results from a command like “logger.info(“Test2” + test[2]);” should appear? But they’re not in the file.
    This line informs about the rule I ran (see the beginning of this reply)

2021-04-11 08:44:07.023 [INFO ] [openhab.event.RuleUpdatedEvent      ] - Rule 'test' has been updated.

But no errors/warnings appear and no “v_string”.

I upload the 3 files (had to change filename of log.7). If there’s anything else I can do, please tell me.events.log (497.8 KB)

Had to cut many lines off due to file size, but shouldn’t matter due to repetitions
openhab7shortened.log (671.4 KB)

same hereopenhab-shortened.log (785.8 KB)

And here’s another more detailed observation:
I can’t open openhab-windows (left part of screenshot) but it still seems to run in the background (tailgate logger still updating, right part of screenshot).

Not sure but maybe this is the relevant information for this problem:

2021-04-11 10:25:46.083 [INFO ] [.reconnect.PeriodicReconnectStrategy] - Try to restore connection to ''. Next attempt in 60000ms

Your old history log shows problems with your JDBC and MQTT configurations. Maybe you’ve fixed them since then. Won’t affect javascript rules.
openhab.log is the “current” version.

The problem is you are using frontail and it showing both openhab and events logs.
The events log is not what we want to see. Event log has too many changes happening in it.
If you log to the openhab.log then the output we see will be what we are testing.

If you ssh to the OH server and run the following command:

tail -f /var/log/openhab/openhab.log

It gives a live output similar to below:
2021-04-12 08:13:22.382 [INFO ] [org.openhab.rule.8e1e6893d6 ] - Hue 128
2021-04-12 08:13:22.383 [INFO ] [org.openhab.rule.8e1e6893d6 ] - Saturation 100
2021-04-12 08:13:22.384 [INFO ] [org.openhab.rule.8e1e6893d6 ] - Brightness 89

This is the rule you will run :

var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);

var test = itemRegistry.getItem("LeuchteHuegross_Farbe").getState().toString().split(",");

logger.info("Test " +  test);
logger.info("Test " +  test[0]);
logger.info("Test " +  test[1]);
logger.info("Test " +  test[2]);

logger.info("Hue " + items["LeuchteHuegross_Farbe"].getHue());
logger.info("Saturation " + items["LeuchteHuegross_Farbe"].getSaturation());
logger.info("Brightness " + items["LeuchteHuegross_Farbe"].getBrightness());

If you do all the above you may be able to get some help as the log files etc you send are not helpful at all. The log files look like you have other problems as well, but that is another story.
Good luck.


Hello Greg,

I ran your rule and it got me the expected output (among way to many error/warning-informations):

2021-04-12 08:10:16.212 [INFO ] [org.openhab.rule.test               ] - Test 36,30,44
2021-04-12 08:10:16.222 [INFO ] [org.openhab.rule.test               ] - Test 36
2021-04-12 08:10:16.225 [INFO ] [org.openhab.rule.test               ] - Test 30
2021-04-12 08:10:16.228 [INFO ] [org.openhab.rule.test               ] - Test 44
2021-04-12 08:10:16.238 [INFO ] [org.openhab.rule.test               ] - Hue 36
2021-04-12 08:10:16.242 [INFO ] [org.openhab.rule.test               ] - Saturation 30
2021-04-12 08:10:16.246 [INFO ] [org.openhab.rule.test               ] - Brightness 44

I then added this line:

testvariable = ("Brightness " + items["LeuchteHuegross_Farbe"].getBrightness());

and to make sure with a string conversion

testvariable = string(("Brightness " + items["LeuchteHuegross_Farbe"].getBrightness()));

Both times the information your put in logger updated, but the value of testvariable didn’t (and didn’t show in fronttail)

That’s because you aren’t logging it.
logger.info("Brightness " + testvariable);

1 Like

Ok, that worked. Now I should be able to continue with my rules :wink:
And learning about the “logger.info”-method is quite helpul since I can track variables with it too; thanks for that, too.

Independently of that I need to find a way to get my system more stable. I’ll try to somehow get rid off the jdbc- and influxdb-warnings and hope that that’ll do the job …

That’s the whole point of logging. To see what is happening in the rules etc.

Good luck

Can’t you use regex? I have no experience with JavaScript but I found it should do regex just fine: Regular expressions - JavaScript | MDN

To get the third number in 123,456,789 your pattern could be


and your result would be the third match.

But knowing you want the third number this may be easier:


Then the result would be your only match.