OK, this is doable but it is probably more appropriate for some other server outside of OH to do it for you (e.g. python script with a database). This is not the sort of problem that OH was designed to solve and keeping a running list of all currently assigned IDs will be challenging.
The ID needs to be unique, but are there any other requirements? For example, do they need to be sequential, a certain number of digits long, random, etc?
That will drive how this would work.
If I assume that the IDs need merely be sequential and you do not have to keep track of already assigned IDs you can do something like the following:
Prerequisites:
- MQTT binding and MQTT Action installed
- Persistence set up and CurrNodeID (see below) persisted with restoreOnStartup
Items:
String RequestID { mqtt="<[config]" } // config to subscribe to request for ID topic, message is the topic to publish the new ID to
Number CurrNodeID
Rules:
import java.util.concurrent.locks.ReentrantLock
val ReentrantLock idLock = new ReentrantLock()
rule "Next ID was requested"
when
Item RequestID received command
then
idLock.lock
try {
val nextId = (CurrNodeID.state as Number) + 1
CurrNodeID.postUpdate(nextId)
publish("brokername", receivedCommand, nextId.toString)
}
catch(Exception e){
logError("ID", "Error calculating next Node ID: " + e.toString)
}
finally {
idLock.unlock
}
end
If you need more than sequential IDs and/or need to guarantee the nodes are unique, OH is not the best place to implement this.
Usual warning, I just typed in the above, there are likely errors.